angular2 ng2 @input和@output理解及示例
angular2@input和@output理解
先做个比方,然后奉上代码
比如:
input,[talk]="someExp"这个标签可以理解为一个专门的监听器,监听父组件传递过来的someExp参数,并存入自身组件的talk变;好像是开了个后门,允许且只允许父组件的someExp进入,一旦进入立刻抓进一个叫talk的牢房,然后子组件中就可以通过@Input来定义这个变量talk然后使用它。
output,(click)="eventHandler($event.rating)这个意思是,当子组件的click事件被触发,就执行父组件的eventHandler函数,并把子组件的参数$event.rating传递给父组件的eventHandler函数;就好像,当小孩子一哭(执行click事件),他的母亲立刻把他抱在怀里(执行母亲的eventHandler),同时母亲获得了小孩子的一些参数($event.rating)
1、@input()
父组件father.component.ts提供数据
import{Component}from"@angular/core"; @Component({ selector:"my-father", templateUrl:"father.html" }) exportclassFatherComponent{ data:Array
模板文件father.html
父组件
//包含子组件,并使用属性传递数据过去
子组件child.component.ts获取数据
import{Component,Input}from"@angular/core"; @Component({ selector:"my-child", templateUrl:"child.html" }) exportclassChildComponent{ //使用@Input获取传递过来的数据 @Input() info:Array
子组件child.html模板文件
- {{item.name}}
2、@Output()
子组件three-link.component.ts
1.引入
import{Component,OnInit,Output,EventEmitter}from"@angular/core";
2.定义输出变量
exportclassThreeLinkComponent{ province:string; //输出一下参数 @Output()provinceOut=newEventEmitter(); constructor(){ this.province="陕西"; } }
3.事件出发,发射变量给父组件
provinceChange(){ //选择省份的时候发射省份给父组件 this.provinceOut.emit(this.province); }
父组件模板
父组件
//函数接受子函数传递过来的变量,子函数中emit的时候触发这个函数。 recPro(event){ this.province=event; }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。