Angular 12: Trigger multiple child components at once

The solution for “Angular 12: Trigger multiple child components at once” can be found here. The following code will assist you in solving the problem.

//Service

@Injectable({
providedIn: ‘root’,
})
export class DoSomethingService {
subject = new Subject();
}

//Parent

export class AppComponent {
constructor(private doSomethingService: DoSomethingService) {}

makeSomethingHappen() {
this.doSomethingService.subject.next();
}
}



//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();
}
}

Thank you for using DeclareCode; We hope you were able to resolve the issue.

More questions on [categories-list]

0
inline scripts encapsulated in