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); } }