TAHA SULTAN TEMURI
TAHA SULTAN TEMURI

Reputation: 5281

Detect Input() Value Change Inside Child (Angular)

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?

Upvotes: 0

Views: 2046

Answers (3)

Suhas Parameshwara
Suhas Parameshwara

Reputation: 1454

You can achieve the functionality using ngOnChanges.

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

Upvotes: 1

Andrew Allen
Andrew Allen

Reputation: 8052

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.

Upvotes: 1

Ramesh Reddy
Ramesh Reddy

Reputation: 10662

Try using setters on the @Input:

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

also, you can use ngOnChanges

Upvotes: 3

Related Questions