Angular父子組件間怎么進行通信?本篇文章給大家介紹一下Angular父子組件傳值方式。
通過Input和Ouput傳值
父組件:html和ts
<app-liftcycle [name]="name" (changeName)="changeName($event)"></app-liftcycle>
public name: string = "jack"; public changeName(value: string) { this.name = value; }
子組件:html和ts
<div (click)="emit()">{{name}}</div>
import { Component, Input, EventEmitter, Output } from '@angular/core'; @Input() name: string; @Output() changeName: EventEmitter<string> = new EventEmitter<string>(); public emit() { this.changeName.emit("修改name屬性"); }
【相關(guān)教程推薦:《angular教程》】
通過setter監(jiān)聽屬性的變化
父組件同上,子組件:
private _name: string = ""; @Input() public get name(): string { return this._name; } public set name(value: string) { this._name = value + "定義結(jié)構(gòu)"; }
通過ngOnChanges鉤子函數(shù)監(jiān)聽輸入屬性的變化
ngOnChanges在監(jiān)聽多個屬性的時候,要比setter的方式簡便一些。
@Input() name: string; ngOnChanges(changes: SimpleChanges): void { (({name}) => { console.log(name.currentValue,name.previousValue); })(changes); }
父組件html中通過模板變量調(diào)用子組件的方法和屬性。
模板變量獲取了子組件的一個引用。 父組件:
<app-liftcycle #child></app-liftcycle> <button (click)="child.childFn()">按鈕</button>
子組件:
public childFn() { console.log("通過模板變量調(diào)用子組件中的方法"); }
父組件通過ViewChild獲取子組件實例
<app-liftcycle [name]="name" (changeName)="changeName($event)" #child></app-liftcycle> <button (click)="childFn()">childFn</button>
@ViewChild("child") child: LiftcycleComponent; public childFn(): void { this.child.childFn(); }
通過service進行通信
service:
import { Subject } from 'rxjs'; import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class CommunService { constructor() {} public commun = new Subject<string>(); communSend() { this.commun.next("send"); } }
父組件:
constructor(private commun: CommunService) { } public send(): void { this.commun.communSend(); }
子組件:
constructor(private commun: CommunService) { this.commun.commun.subscribe((value) => {console.log(value)}); }
父組件傳遞方法
父組件通過屬性傳遞給子組件方法,子組件進行調(diào)用,一般不推薦,React采用這種通信方式。 可能是基于this的綁定錯綜復雜,所以angular不太推薦。React Hooks的出現(xiàn)也有一部分原因 是class類的this錯綜復雜。 父組件:
<app-liftcycle [send]="send.bind(this)"></app-liftcycle>
public name: string = "jack"; public send(): void { console.log(this.name); }
子組件:
<button (click)="childSend()">childSend</button>
@Input() send: Function; public childSend() { this.send(); }