本文主要介紹了angular2 ng2 @input和@output理解及示例,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧,希望能幫助到大家。
angular2 @input和@output理解
先做個比方,然后奉上代碼
比如:
<talk-cmp [talk]="someExp" (rate)="eventHandler($event.rating)">
input, [talk]="someExp" 這個標(biāo)簽可以理解為一個專門的監(jiān)聽器,監(jiān)聽父組件傳遞過來的someExp參數(shù),并存入自身組件的talk變;好像是開了個后門,允許且只允許父組件的someExp進(jìn)入,一旦進(jìn)入立刻抓進(jìn)一個叫talk的牢房,然后子組件中就可以通過@Input來定義這個變量talk然后使用它。
output ,(click)="eventHandler($event.rating) 這個意思是, 當(dāng)子組件的click事件被觸發(fā),就執(zhí)行父組件的eventHandler函數(shù),并把子組件的參數(shù)$event.rating傳遞給父組件的eventHandler函數(shù);就好像,當(dāng)小孩子一哭(執(zhí)行click事件),他的母親立刻把他抱在懷里(執(zhí)行母親的eventHandler),同時母親獲得了小孩子的一些參數(shù)($event.rating)
1、@input()
父組件 father.component.ts 提供數(shù)據(jù)
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> // 包含子組件, 并使用屬性傳遞數(shù)據(jù)過去 <my-child [info]="data"></my-child>
子組件 child.component.ts 獲取數(shù)據(jù)
import {Component, Input} from "@angular/core"; @Component({ selector: "my-child", templateUrl: "child.html" }) export class ChildComponent { // 使用@Input獲取傳遞過來的數(shù)據(jù) @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; // 輸出一下參數(shù) @Output() provinceOut = new EventEmitter(); constructor() { this.province = "陜西"; } }
3. 事件出發(fā),發(fā)射變量給父組件
provinceChange() { // 選擇省份的時候發(fā)射省份給父組件 this.provinceOut.emit(this.province); }
父組件模板
<!--三級聯(lián)動組件--> <three-link (provinceOut)="recPro($event)"></three-link>
父組件
// 函數(shù)接受子函數(shù)傳遞過來的變量, 子函數(shù)中emit的時候觸發(fā)這個函數(shù)。 recPro(event) { this.province = event; }
相關(guān)推薦:
JS實(shí)現(xiàn)點(diǎn)擊下拉菜單把選擇的內(nèi)容同步到input輸入框內(nèi)的實(shí)例
JS點(diǎn)擊下拉菜單把選擇的內(nèi)容同步到input輸入框內(nèi)實(shí)現(xiàn)方法
使用output標(biāo)簽標(biāo)注JavaScript返回值的實(shí)例分析
以上就是angular2 input和output解析的詳細(xì)內(nèi)容,更多請關(guān)注php中文網(wǎng)其它相關(guān)文章!
每個人都需要一臺速度更快、更穩(wěn)定的 PC。隨著時間的推移,垃圾文件、舊注冊表數(shù)據(jù)和不必要的后臺進(jìn)程會占用資源并降低性能。幸運(yùn)的是,許多工具可以讓 Windows 保持平穩(wěn)運(yùn)行。
微信掃碼
關(guān)注PHP中文網(wǎng)服務(wù)號
QQ掃碼
加入技術(shù)交流群
Copyright 2014-2025 http://www.miracleart.cn/ All Rights Reserved | php.cn | 湘ICP備2023035733號