angular2 @input和@output理解
先做個比方,然后奉上代碼
比如:
<talk-cmp [talk]="someExp" (rate)="eventHandler($event.rating)">
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"})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.html
<h1>父組件</h1>// 包含子組件, 并使用屬性傳遞數據過去<my-child [info]="data"></my-child>
子組件 child.component.ts 獲取數據
import {Component, Input} from "@angular/core";@Component({ selector: "my-child", templateUrl: "child.html"})export class ChildComponent { // 使用@Input獲取傳遞過來的數據 @Input() info: Array<Object>; constructor() { }}
子組件 child.html模板文件
<ul> <li *ngFor="let item of info"> {{item.name}} </li></ul>
2、@Output()
子組件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;}
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答