0
votes

I just need to update child component when Input value changes , the child component has some input parameters which set some local variables inside ngInit() but the issue is the parent when change the input parameters the child does not update because ngInit() only trigger once it is initialize.

Inside Parent

<app-site-parameter-tbl *ngIf="siteTbl==true" [siteParameterTDataSet]="siteParameterDataSet" [siteParameterTGridColumns]="siteParameterColumns" [siteParameterFoot]="siteParameterFooter" [siteParameterT]="siteParameterTbl" [model]="siteModel" [bckColor]="this.tabBackColor"></app-site-parameter-tbl>

On some trigger events the parent changes these properties (as input of child)

Parent Ts

method(ds, columns, footer) {

    this.siteParameterDataSet = ds;
    this.siteParameterColumns = columns;
    this.siteParameterFooter = footer;
}

This hit only once even after changing input values

Child ts

@Input() siteParameterT: boolean;
@Input() model: SiteModel;
@Input() siteParameterFoot: [];
@Input() siteParameterTGridColumns: [];
@Input() siteParameterTDataSet: any;

ngOnInit() {
    debugger;
    //setting local variables then they will render inside html

    this.siteParameter = this.siteParameterT;
    this.site = this.model;
    this.foot = this.siteParameterFoot;
    this.dataSet = this.siteParameterTDataSet;
}

Please help , if I can use Input properties directly inside html then how come can i make changes to it? Help me know how to notify when Input changes?

3
Do this assignment inside ngOnChanges. - cs95
@TAHASULTANTEMURI Look at this link stackoverflow.com/a/36653734/7321113 - Abhishek
@TAHASULTANTEMURI you can try to use ChangeDetectionStrategy on push in this scenario: angular.io/api/core/ChangeDetectionStrategy - tutorialfeed
thank you @Abhishek ngOnChanges solved my problem ,also its one stop solution i can check property using switch then update - TAHA SULTAN TEMURI

3 Answers

3
votes

Try using setters on the @Input:

@Input('siteParameterT')
set siteParameterT(value: boolean) {
    this.siteParameter = value
}

also, you can use ngOnChanges

1
votes

hook into ngOnChanges instead:

example usage

  @Input() employee: Employee

  ngOnChanges(changes: SimpleChanges) {
    /** Fire any time employee changes */
    if (changes.employee && changes.employee.currentValue) {
      this.formGroup.patchValue(this.employee)
    }
  }

There's also a decorator method. Though note the TypeScript decorator is experimental.

1
votes

You can achieve the functionality using ngOnChanges.

 public ngOnChanges(changes: SimpleChanges): void {
    this.siteParameter = changes.siteParameter;
    etc.,
  }