angular父子组件通信详解
用到的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-cli:1.0.0-beta.28.3升级到@angular/cli:1.0.0
本篇文章主要介绍了详解从angular-cli:1.0.0-beta.28.3升级到@angular/cli:1.0.0,具有一定的参考价值,有兴趣的可以了解一下2017-05-05Angular 4.x+Ionic3踩坑之Ionic3.x pop反向传值详解
这篇文章主要给大家介绍了关于Angular 4.x+Ionic3踩坑之Ionic3.x pop反向传值的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧。2018-03-03使用typescript开发angular模块并发布npm包
本篇文章主要介绍了使用typescript开发angular模块并发布npm包,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧2018-04-04Angularjs实现带查找筛选功能的select下拉框示例代码
这篇文章主要介绍了Angularjs实现带查找筛选功能的select下拉框的详细过程及示例代码,文中通过示例介绍的很详细,相信会对大家学习使用Angularjs具有一定的参考借鉴价值,有需要的朋友们可以一起来看看。2016-10-10
最新评论