学无先后,达者为师

网站首页 前端文档 正文

angular父子组件通信详解_AngularJS

作者:桐溪漂流   更新时间: 2022-03-13 前端文档

用到的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 { }
}

效果

效果图

总结

原文链接:https://blog.csdn.net/qq564280420/article/details/121959412

栏目分类
最近更新