Angular 2/Ionic 2 @input和@output理解
本篇博客為轉載,看了原作者寫的之后十分通透,就直接搬過來了,原地址:https://segmentfault.com/a/1190000007890167(侵刪)十分感謝原作者
先說說如何區分子組件、父組件。比如說我有一個組件A,他的選擇器是cmpA,然后B組件里的html文件里用到了cmpA,那么A組件就是子組件,B組件就是父組件。
做個比方,然后奉上代碼
比如:
input, [talk]="someExp" 這個標簽可以理解為一個專門的監聽器,監聽父組件傳遞過來的someExp參數,并存入自身組件的talk變量;好像是開了個后門,允許且只允許父組件的someExp進入,一旦進入立刻抓進一個叫talk的牢房,然后子組件中就可以通過@Input來定義這個變量talk然后使用它。
output ,(click)="eventHandler($event.rating) 這個意思是, 當子組件的click事件被觸發,就執行父組件的eventHandler函數,并把子組件的參數$event.rating傳遞給父組件的eventHandler函數;就好像,當小孩子一哭(執行click事件),他的母親立刻把他抱在懷里(執行母親的eventHandler),同時母親獲得了小孩子的一些參數($event.rating),上面的[talk]就相當于母親給孩子的禮物,但是孩子只能通過@input()去拿。
我的理解就是: input是子組件接受父組件傳進來的參數,output是子組件通過觸發事件向父組件傳數據
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; }3.另外一個父組件中訪問子組件中的方法
子組件CircleComponent中定義了 getColorRedFun(i)方法,父組件中想調用這個方法。
1、html中添加標記 #circleComponent
2、使用@ViewChild訪問子組件
3、ngAfterViewInit()以后才可以訪問到獲取的子組件
4、就可以通過 this.circleComponent訪問子組件中的屬性和方法了。
?
總結
以上是生活随笔為你收集整理的Angular 2/Ionic 2 @input和@output理解的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ArcGIS JS API中切换页面后组
- 下一篇: dojo发布者订阅者模式(topic.p