Input
- 子组件中定义可接受的属性,可以用来父组件给子组件传递数据
Output
- 子组件中定义输出的属性,该属性需要是 EventEmitter 的事件类型,用来通知父组件做出相应的操作
EventEmitter
- 用在带有 @Output 指令的组件中,以同步或异步方式发出自定义事件,并通过订阅实例来为这些事件注册处理器。
列表渲染子组件,点击子组件通知父组件进行操作
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 { } }
本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注的更多内容!