简体   繁体   English

Angular变化检测ngFor

[英]Angular change detection ngFor

I have an array called peoples on my tab view.我的标签视图上有一个名为peoples的数组。 I need to change the array items based on a change function.我需要根据更改 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() ;虽然更改 function 成功运行,并且在控制台上的每次更改后以不同方式打印数组,但视图本身并没有从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.首先你在 category.name 上使用[(ngModel)]="category.name"(ngModelChange)="loadpeople(category.name)" category.name但是接下来你遍历category并得到cat.name ,所以不能有category.name元素,如果它是一个数组。

Second I will just use (change) instead of [ngModel] + (ngModelChange) according to what you show, because as said before, category.name cannot return anything.其次,我将根据您显示的内容使用(change)而不是[ngModel] + (ngModelChange) ,因为如前所述, category.name不能返回任何内容。

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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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