Angular組件間怎么通信?下面本篇文章給大家介紹一下Angular組件之間通信的5種方法,有需要的可以參考~
組件是angular的構建單元,在項目中為了保證組件之間的數據能夠來回的傳遞,angular封裝了一些能夠實現組件之間通信的方法。【相關教程推薦:《angular教程》】
一、父組件通過輸入型綁定將數據傳遞給子組件
父組件
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、使用一個輸入屬性的 setter,以攔截父組件中值的變化,并采取行動。
child1.component.ts
@Input() set name(name: string) { this._name = name.trim(); } private _name: string;
2、使用 ngOnChanges()鉤子函數來監測輸入屬性值的變化并做出回應。當需要監視多個、交互式輸入屬性的時候,本方法比用屬性的 setter 更合適。
child1.component.ts
ngOnChanges(changes: SimpleChanges): void { console.log(changes); }
我們可以通過angular官方提供的類型描述文件了解到SimpleChange的相關屬性:
二、父組件監聽子組件的事件獲取子組件傳遞給父組件的值
子組件暴露一個EventEmitter(帶有@Output裝飾器)屬性,當事件發生時,子組件利用該屬性emit事件往父組件發射值。父組件綁定到這個事件屬性,并在事件發生時作出回應。
子組件
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)在模板中讀取子組件的屬性和調用子組件的方法
子組件
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>
局限性:父組件-子組件的連接必須全部在父組件的模板中進行。如果父組件的類需要讀取子組件的屬性值或調用子組件的方法,就不能使用本地變量方法。
四、父組件調用@ViewChild
當父組件的類需要讀取子組件的屬性值或調用子組件的方法,就不能使用本地變量方法;如果有這種需求時,我們可以通過@ViewChild把子組件注入到父組件中;
父組件
parent.component.ts
@ViewChild(Child1Component) private child1Component!: Child1Component;
可以通過child1Component變量訪問子組件的屬性和方法;
五、利用共享服務實現任意組件之間的通信
為了實現任意組件之間的通信,我們可以結合Rxjs中的BehaviorSubject對象來創建一個共享服務;BehaviorSubject的使用可以參考這篇博客blog.tcs-y.com/2019/10/08/…
創建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的構造函數中注入服務并設置data
child1.component.ts
constructor(private dataService: DataService) {} // 設置data的值 changeData(): void { this.dataService.data.next(10); }
child1.component.html
<button (click)="changeData()">Click</button>
在組件2的構造函數中注入服務并訂閱data
child2.component.ts
constructor(private dataService: DataService) { this.dataService.data.subscribe(value => { console.log(value); // 10 }); }