Home > Back-end >  Angular 12: Trigger multiple child components at once
Angular 12: Trigger multiple child components at once

Time:04-12

I have a situation where Parent component is having 5 DIFFERENT CHILD COMPONENTS rendered, and on a button click from parent or a value change of parent, all 5 child components should do something (execute a method)

Please suggest a stand practice in Angular 12 or 13 versions

CodePudding user response:

I would suggest a shared service and an RXJS Subject.

Here's an example: https://stackblitz.com/edit/angular-ivy-fvllm7?file=src/app/app.component.ts

Service

@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();
  }
}
  • Related