angular2 @input和@output理解css
先作个比方,而后奉上代码
好比:html
<talk-cmp [talk]="someExp" (rate)="eventHandler($event.rating)">
input, [talk]="someExp" 这个标签能够理解为一个专门的监听器,监听父组件传递过来的someExp参数,并存入自身组件的talk变量;好像是开了个后门,容许且只容许父组件的someExp进入,一旦进入马上抓进一个叫talk的牢房,而后子组件中就能够经过@Input来定义这个变量talk而后使用它。node
output ,(click)="eventHandler($event.rating) 这个意思是, 当子组件的click事件被触发,就执行父组件的eventHandler函数,并把子组件的参数$event.rating传递给父组件的eventHandler函数;就好像,当小孩子一哭(执行click事件),他的母亲马上把他抱在怀里(执行母亲的eventHandler),同时母亲得到了小孩子的一些参数($event.rating),上面的[talk]就至关于母亲给孩子的礼物,可是孩子只能经过@input()去拿。angular2
一、@input()ionic
父组件 father.component.ts 提供数据函数
import {Component} from "@angular/core"; @Component({ selector: "my-father", templateUrl: "father.html" }) export class FatherComponent { data: Array<Object>; constructor() { this.data = [ { "id": 1, "name": "html" }, { "id": 2, "name": "css" }, { "id": 3, "name": "angular" }, { "id": 4, "name": "ionic" }, { "id": 5, "name": "node" } ] } }
模板文件 father.htmlthis
<h1>父组件</h1> // 包含子组件, 并使用属性传递数据过去 <my-child [info]="data"></my-child>
子组件 child.component.ts 获取数据code
import {Component, Input} from "@angular/core"; @Component({ selector: "my-child", templateUrl: "child.html" }) export class ChildComponent { // 使用@Input获取传递过来的数据 @Input() info: Array<Object>; constructor() { } }
子组件 child.html模板文件component
<ul> <li *ngFor="let item of info"> {{item.name}} </li> </ul>
二、@Output()htm
子组件three-link.component.ts
1. 引入 import {Component, OnInit, Output, EventEmitter} from "@angular/core"; 2. 定义输出变量 export class ThreeLinkComponent { province: string; // 输出一下参数 @Output() provinceOut = new EventEmitter(); constructor() { this.province = "陕西"; } } 3. 事件出发,发射变量给父组件 provinceChange() { // 选择省份的时候发射省份给父组件 this.provinceOut.emit(this.province); }
父组件模板
<!--三级联动组件--> <three-link (provinceOut)="recPro($event)"></three-link>
父组件
// 函数接受子函数传递过来的变量, 子函数中emit的时候触发这个函数。 recPro(event) { this.province = event; }
再添加一个父组件中访问子组件中的方法
子组件CircleComponent中定义了 getColorRedFun(i)方法,父组件中想调用这个方法。
一、html中添加标记 #circleComponent
二、使用@ViewChild访问子组件
三、ngAfterViewInit()之后才能够访问到获取的子组件
四、就能够经过 this.circleComponent访问子组件中的属性和方法了。
html <page-circle #circleComponent></page-circle> ts export class HomePage { @ViewChild("circleComponent") circleComponent: CircleComponent; ngAfterViewInit() { console.log(this.circleComponent); this.circleComponent.getColorRedFun(4); } }