Search code examples
angularparent-childonchangereload

Angular7 pass new data to child component when parent has action


Parent contain a child component and a button

Parent contains a string color: [color]=color

when clicked on the button,

the data is passed to the child and trigger ngOnChanges

parent.html

<button (click)=>'changeColor()'>Change Color </button>
<app-child [color]=color></app-child>

parent.ts

color = {color: 'blue'}
changeColor(){
  this.color.color = 'red'
}

child.ts

@Input() public color: string;
ngOnChanges() {
  console.log('onchange')
}

child.html

<div>color.color</div>

The ngOnChanges is not triggered but the html did react to the change


Solution

  • this.color= Object.assign({}, this.color); will trigger the onchange when passing an object