概述
用到的api
Input
- 子组件中定义可接受的属性,可以用来父组件给子组件传递数据
Output
- 子组件中定义输出的属性,该属性需要是 EventEmitter 的事件类型,用来通知父组件做出相应的操作
EventEmitter
- 用在带有 @Output 指令的组件中,以同步或异步方式发出自定义事件,并通过订阅实例来为这些事件注册处理器。
简单的例子
列表渲染子组件,点击子组件通知父组件进行操作
person.ts
export interface Person { name: string; age: number; sex: string; }
父组件
import { Component, OnInit } from '@angular/core'; import { Person } from './person'; @Component({ selector: 'app-comp-parent', template: ` <app-comp-child *ngFor="let person of personList" (itemClick)="onItemClick($event)" [data]="person" ></app-comp-child> `, }) export class CompParentComponent implements OnInit { personList: Person[] = [ { name: '张三', age: 21, sex: '男' }, { name: '李四', age: 25, sex: '男' }, { name: '李莉', age: 20, sex: '女' }, ]; constructor(){ } ngOnInit(): void { } onItemClick(item: Person){ console.log('click-person: ', item); } }
子组件
import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core'; import { Person } from './person'; @Component({ selector: 'app-comp-child', template: ` <div (click)="itemClick.emit(data)"> Name: {{ data.name }} Age: {{ data.age }} Sex: {{ data.sex }} </div> `, }) export class CompChildComponent implements OnInit { @Input() data!: Person; @Output() itemClick = new EventEmitter(); constructor(){ } ngOnInit(): void { } }
效果
总结
本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注靠谱客的更多内容!
最后
以上就是美满篮球为你收集整理的angular父子组件通信详解的全部内容,希望文章能够帮你解决angular父子组件通信详解所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复