简体   繁体   中英

Angular change detection ngFor

I have an array called peoples on my tab view. I need to change the array items based on a change function. While the change function is working successfully and printing the array differently after each change on the console, the view itself is not changing from the initial value assigned from ngInit() ;

ngOnInit(){
  this.someservice.loadallpeople().subscribe(data=>{
    this.peoples=data.Data;
  });
}

loadpeople(category:any){
  this.someservice.getpeoplebycat(category).subscribe(data=>{
    this.peoples=data.Data;
  });
}
<select [(ngModel)]="category.name"
        (ngModelChange)="loadpeople(category.name)">  
  <option *ngFor="let cat of category">{{category.name}} </option>
</select>  
    
<div *ngFor="let people of peoples">
  <span>{{people.name}}</span>
</div>

I have used some methods but none of them seems to work. Any small help will be appreciated.

Some things are not clear on what you show.

First you use [(ngModel)]="category.name" and (ngModelChange)="loadpeople(category.name)" on category.name , but next you iterate over category and you get cat.name , so there cannot be a category.name element if it's an array.

Second I will just use (change) instead of [ngModel] + (ngModelChange) according to what you show, because as said before, category.name cannot return anything.

So with all this updates, I will do something like this

ngOnInit(){
  this.someservice.loadallpeople().subscribe(data=>{
    this.peoples=data.Data;
  });
}

loadpeople(event){
  this.someservice.getpeoplebycat(event.target.value).subscribe(data=>{
    this.peoples=data.Data;
  });
}
<select (change)="loadpeople($event)">  
  <option *ngFor="let cat of category">{{cat.name}} </option>
</select>  
    
<div *ngFor="let people of peoples">
  <span>{{people.name}}</span>
</div>

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