简体   繁体   中英

Angular: input binding not updating

I am currently having issues trying to bind a list to an input object in Angular. I expect the interpolated value in the child to update every time I add to the list but instead, the original loaded values remained unchanged in the view. Even the OnChange doesn't trigger, I have been wrestling with this for hours any assistance would be appreciated.

Parent

<main-task-list [in-list]='list_values'></main-task-list>
@Component({
   selector: 'main-app',
   templateUrl: './main-app.component.html',
   styleUrls: ['./main-app.component.sass']
})
export class MainAppComponent implements OnInit {
  list_values = [ 10, 20, 30 ]

   add_to_list(){
      this.list_values.push(12)
      console.log( this.list_values )
   }
}

Child

<div>{{in_list}}</div>
@Component({
  selector: 'main-task-list',
  templateUrl: './main-task-list.component.html',
  styleUrls: ['./main-task-list.component.sass']
})
export class MainTaskListComponent implements OnInit {
  @Input( 'in-list') in_list: number[] | null = null

  ngOnChanges( changes: SimpleChanges ){
     console.log('re render')
  }
}

The reference of you item doesn't change when you push value in it. It need to change. try to create a new item and the ngOnChange will trigger again:

this.list_values = [...this.list_values,12]

instead of

this.list_values.push(12)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM