Angular組件間怎么通信?下面本篇文章給大家介紹一下Angular組件之間通信的5種方法,有需要的可以參考~
組件是angular的構(gòu)建單元,在項(xiàng)目中為了保證組件之間的數(shù)據(jù)能夠來回的傳遞,angular封裝了一些能夠?qū)崿F(xiàn)組件之間通信的方法?!鞠嚓P(guān)教程推薦:《angular教程》】
一、父組件通過輸入型綁定將數(shù)據(jù)傳遞給子組件
父組件
parent.component.ts
age = 18; name = ' xiaoming '
parent.component.html
<app-child-1 [age]="age" [name]="name"></app-child-1>
子組件
child1.component.ts
@Input() age!: number;
截聽輸入屬性值的變化
1、使用一個(gè)輸入屬性的 setter,以攔截父組件中值的變化,并采取行動(dòng)。
child1.component.ts
@Input() set name(name: string) { this._name = name.trim(); } private _name: string;
2、使用 ngOnChanges()鉤子函數(shù)來監(jiān)測輸入屬性值的變化并做出回應(yīng)。當(dāng)需要監(jiān)視多個(gè)、交互式輸入屬性的時(shí)候,本方法比用屬性的 setter 更合適。
child1.component.ts
ngOnChanges(changes: SimpleChanges): void { console.log(changes); }
我們可以通過angular官方提供的類型描述文件了解到SimpleChange的相關(guān)屬性:
二、父組件監(jiān)聽子組件的事件獲取子組件傳遞給父組件的值
子組件暴露一個(gè)EventEmitter(帶有@Output裝飾器)屬性,當(dāng)事件發(fā)生時(shí),子組件利用該屬性emit事件往父組件發(fā)射值。父組件綁定到這個(gè)事件屬性,并在事件發(fā)生時(shí)作出回應(yīng)。
子組件
child1.component.ts
@Output() voted = new EventEmitter<boolean>(); emitValue(): void { this.voted.emit(true); }
child1.component.html
<button (click)="emitValue()">Click</button>
父組件
parent.component.html
<app-child-1 [age]="age" [name]="name" (voted)="getChildParam($event)"></app-child-1>
parent.component.ts
getChildParam(value: boolean): void { console.log(value); // true }
三、父組件通過本地變量(#varibleName)在模板中讀取子組件的屬性和調(diào)用子組件的方法
子組件
child1.component.ts
address = 'Shanghai'; setAddress(address: string): void { this.address = address; }
父組件
parent.component.html
<app-child-1 [age]="age" [name]="name" (voted)="getChildParam($event)" #child1Component></app-child-1> <div>{{child1Component.address}}</div> <button (click)="child1Component.setAddress('Beijing')">Click</button>
局限性:父組件-子組件的連接必須全部在父組件的模板中進(jìn)行。如果父組件的類需要讀取子組件的屬性值或調(diào)用子組件的方法,就不能使用本地變量方法。
四、父組件調(diào)用@ViewChild
當(dāng)父組件的類需要讀取子組件的屬性值或調(diào)用子組件的方法,就不能使用本地變量方法;如果有這種需求時(shí),我們可以通過@ViewChild把子組件注入到父組件中;
父組件
parent.component.ts
@ViewChild(Child1Component) private child1Component!: Child1Component;
可以通過child1Component變量訪問子組件的屬性和方法;
五、利用共享服務(wù)實(shí)現(xiàn)任意組件之間的通信
為了實(shí)現(xiàn)任意組件之間的通信,我們可以結(jié)合Rxjs中的BehaviorSubject對象來創(chuàng)建一個(gè)共享服務(wù);BehaviorSubject的使用可以參考這篇博客blog.tcs-y.com/2019/10/08/…
創(chuàng)建dataService.ts
import {BehaviorSubject} from 'rxjs'; import { Injectable} from '@angular/core'; @Injectable( {providedIn: 'root'} ) export class DataService { data: BehaviorSubject<number> = new BehaviorSubject<number>(0); }
在組件1的構(gòu)造函數(shù)中注入服務(wù)并設(shè)置data
child1.component.ts
constructor(private dataService: DataService) {} // 設(shè)置data的值 changeData(): void { this.dataService.data.next(10); }
child1.component.html
<button (click)="changeData()">Click</button>
在組件2的構(gòu)造函數(shù)中注入服務(wù)并訂閱data
child2.component.ts
constructor(private dataService: DataService) { this.dataService.data.subscribe(value => { console.log(value); // 10 }); }