0
votes

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

2

2 Answers

0
votes

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

0
votes

The logic in the code is good, but the syntax is off:

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

should be:

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

Notice in the first line I removed the > and in the second, I added quotes. I also added the closing tag in the first line as the text in between tags is the text of the button.

Also, in your child component, the copde is missing the interpolation:

<div>{{color}}</div>

Check this page: https://angular.io/guide/template-syntax