Angular12:一次触发多个子组件
Angular 12: Trigger multiple child components at once
我有这样一种情况,父组件呈现了 5 个不同的子组件,并且在父组件单击按钮或父组件的值发生更改时,所有 5 个子组件都应该做某事(执行一个方法)
请推荐Angular 12 或 13 版本
的站立练习
我建议共享服务和 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>();
}
Parent
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>
Children
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();
}
}
我有这样一种情况,父组件呈现了 5 个不同的子组件,并且在父组件单击按钮或父组件的值发生更改时,所有 5 个子组件都应该做某事(执行一个方法)
请推荐Angular 12 或 13 版本
的站立练习我建议共享服务和 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>();
}
Parent
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>
Children
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();
}
}