Trigger a change to children components in Angular 2, even though the data/state is not changes

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?

Upvotes: 2

Views: 6390

Answers (1)

user184994
user184994

Reputation: 18301

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

Upvotes: 13

Related Questions