'Angular ngOnChanges not working when I update child componenet property from parent component

app.component.ts

import { Component, ViewChild } from '@angular/core';
import { ButtonComponent } from './button/button.component';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  @ViewChild('btn1') btn1!:ButtonComponent;
  @ViewChild('btn2') btn2!:ButtonComponent;

  updateOption() {
    this.btn2.disabledOnClick = 10000;
  }
}

app.component.html

<button app-button #btn1 [disabledOnClick] = 300 (click)="updateOption();">
    Button111
</button>
<br><br>
<button app-button #btn2 [disabledOnClick] = 500>
    Button222
</button>

button.component.ts

import { Component, Input, OnInit, ElementRef, Renderer2, OnChanges, SimpleChanges } from '@angular/core';

type ButtonOptionType = boolean | number;

@Component({
  selector: '[app-button]',
  templateUrl: './button.component.html'
})
export class ButtonComponent implements OnInit, OnChanges {
  @Input() disabledOnClick: ButtonOptionType = false; 

  constructor(
    private elementRef:ElementRef,
    private renderer: Renderer2
  ) {}

  ngOnInit(): void {
    if(this.disabledOnClick !== false) {
      this.setDisabled(this.disabledOnClick);
    }
  }

  ngOnChanges(changes: SimpleChanges): void {
    console.log('ngOnChanges!!!', changes);
  }

  setDisabled(option: ButtonOptionType) {
    this.renderer.listen(this.elementRef.nativeElement, 'click', () => {
      this.elementRef.nativeElement.setAttribute('disabled', '');
      console.log('option', option);
      if(typeof option === 'number') {
        setTimeout(() => {
          this.elementRef.nativeElement.removeAttribute('disabled');
        }, option);
      }
    });
  }
}

I have made two button components to test ngOnChanges
and added a click event on the button1 so that it can change the property value of the button2.

Unfortunately ngOnChange function does not trigger but btn2.disabledOnClick value changed.
So how can I have the child component detect value changes?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source