我遇到这样的情况:父组件呈现5个不同的子组件,在父组件的按钮单击或父组件的值更改时,所有5个子组件都应该执行一些操作(执行一个方法)。
请建议在角度12或13版本的站立练习。
发布于 2022-04-12 05:30:48
我建议提供共享服务和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://stackoverflow.com/questions/71837296
复制相似问题