Skip to content Skip to sidebar Skip to footer

Angular 2+: Update @Input Property When Parent Value Changes

I have a parent and child component where the parent is passing an object to the child through the @Input decorator. The problem is the child gets the parent data only once, then a

Solution 1:

On parent component change, do change in child component too

Here is how you can do with OnChanges interface which detects changes in the component

In parent.component.html

<app-child [child_name]="name"></app-child>

In child.component

export class ChildComponent implements OnChanges {

  @Input('child_name') name: string
  text: string
  constructor() { }

  // on every change of @input 'name', this method will be triggered
  ngOnChanges() {
    this.text = 'Hi ' + this.name
  }

}

DEMO


Solution 2:

The data will be updated when whole reference will be updated. If you just update some properties inside that object, it will not be triggered. You need to change the reference of the passed object.

Example

<child [data]="myData"></child>

If you will update myData.name = "Test", it will not be triggered. You need to do something

this.myData = changedData;

A workaround can be using DoCheck lifecycle hook and try to check the property change manually. But generally it is more handy to change the reference.


Solution 3:

if you want to get update value from parent compoent than you need to add changeDetection: ChangeDetectionStrategy.OnPush in your child component

Note: OnPush works by comparing references of the inputs of the component

@Component({
  selector: 'abc',
  templateUrl: 'component.html',
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class childComponent {
   //below get updated value every time value changes in parent  
   @Input() inputFromParent: string;
}

in parent , use child component abc

 <abc [inputFromParent]="passdata"></abc>

in parent ts this.inputFromParent = newData;//done after first init

now if you change value of passdata then it will change value in childcomponent property too.

Ref : Understanding Change Detection Strategy in Angular


Solution 4:

your parent comp html looks like :

<div>
        <span (click)="expandAllClient = true "> EXPAND </span>
        <span (click)="expandAllClient = false"> COLLAPSE </span>
</div>
<div>
    <child-comp [expandAll]="expandAllClient"(flagChanged)="flagChanged($event)"></child-comp>
</div>

and dont forget to add :

@Input() expandAll: boolean = false; in your ts file

and in child comp you can directly use expandall(here) in all your operation like:

<div [ngClass]="{'openPanel':  expandAll}></div>

here openpanel class will get applied if you have clicked EXPAND span in parent component


Solution 5:

Try to get the changes by ngOnChanges

use it in the child component

  ngOnChanges(changes: import("@angular/core").SimpleChanges): void {

}

Post a Comment for "Angular 2+: Update @Input Property When Parent Value Changes"