我有這樣一種情況,即父組件渲染了 5 個不同的子組件,并且在從父組件單擊按鈕或父組件的值更改時,所有 5 個子組件都應該做一些事情(執行一個方法)
請建議在 Angular 12 或 13 版本中進行站立練習
uj5u.com熱心網友回復:
我會建議一個共享服務和一個 RXJS Subject。
這是一個例子:https ://stackblitz.com/edit/angular-ivy-fvllm7?file=src/app/app.component.ts
服務
@Injectable({
providedIn: 'root',
})
export class DoSomethingService {
subject = new Subject<void>();
}
家長
export class AppComponent {
constructor(private doSomethingService: DoSomethingService) {}
makeSomethingHappen() {
this.doSomethingService.subject.next();
}
}
<button (click)="makeSomethingHappen()">CLICK ME</button>
<app-one></app-one>
<app-two></app-two>
<app-three></app-three>
孩子們
export class OneComponent implements OnInit {
message = 'Component one standing by...';
sub = new Subscription();
constructor(private doSomethingService: DoSomethingService) {}
ngOnInit() {
this.sub = this.doSomethingService.subject.subscribe(() =>
this.doSomething()
);
}
doSomething() {
this.message = 'Component one did something!';
}
ngOnDestroy() {
this.sub.unsubscribe();
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/464232.html
