2

I have this parent components, that has a Boolean attribute, that can be set by user through a button in UI.

I have a recursive set of children components, a tree in fact, that need to response to change of that Boolean attribute, even when the value of that Boolean attribute is not changed, but user has pressed that button.

In other words, even if that Boolean attribute is false, and user clicks that button, and because of some logic the Boolean attribute is not changed at all and remains false, I still want the children components to be notified.

I'm using ngOnChanges and I'm trying to trigger the event manually.

But in case of false to false, which means no change, the ngOnChanges on children components is not called.

What do I miss here?

8
  • 1
    Why voting to close? Commented Jul 6, 2018 at 21:11
  • Why not use an EventEmitter? Commented Jul 6, 2018 at 21:12
  • @user184994, EventEmitter sends the event from children to parent. I want to send the event from parent to children. Commented Jul 6, 2018 at 21:13
  • Why not use a Subject or Observable then, and pass the subject as an Input to the child? Commented Jul 6, 2018 at 21:17
  • Can you guide me to a sample of that? Commented Jul 6, 2018 at 21:18

1 Answer 1

13

You can pass a Subject as an input to the child components.

In your parent component, create a Subject, like so:

import { Component } from '@angular/core'; import { Subject } from 'rxjs'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: [ './app.component.css' ] }) export class AppComponent { subject = new Subject<string>(); handleClick() { // This will send a message via the subject this.subject.next("TEST"); } // Complete the subject when your component is destroyed to avoid memory leaks ngOnDestroy() { this.subject.complete(); } } 

And pass it to the child component:

<hello [notifier]="subject"></hello> 

In your child component, subscribe to the Subject, and do whatever you need to do in the subscribe callback:

import { Component, Input } from '@angular/core'; import { Subject } from 'rxjs'; @Component({ selector: 'hello', template: `<h1>Hello {{name}}!</h1>`, styles: [`h1 { font-family: Lato; }`] }) export class HelloComponent { @Input() notifier: Subject<any>; ngOnInit() { if (this.notifier != null) { this.notifier.subscribe((event) => { // This will be logged every time the subject.next is called. console.log("HelloComponent heard", event); }) } } } 

Here is a StackBlitz example

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.