简体   繁体   中英

Unshifted array elements not shown in *ngFor in angular5

I am trying to Listing all countries that from a JSON response in a ngFor , Also tried to move US and Canada to the top of the list using unshift .

Here is the code

let newData = this.countries.filter(item => item.CountryCode!=='CA');
newData.unshift({idCity:39,countryName:'Canada',countryCode:'CA'});
newData = newData.filter(item => item.CountryCode!=='US');
newData.unshift({idCity:231,countryName:'United States',countryCode:'US'});
this.countries = newData;
console.log(this.countries);

I am getting the proper result in console.log(this.countries); But the unshifted objects not showing in the ngFor

<div class="drop_option col-xs-12" *ngFor="let countries of countries; let i = index" (click)="fetchCountries(i,$event)">{{countries.CountryName}}</div>

It's just a typo.

newData.unshift({idCity:39,countryName:'Canada',countryCode:'CA'});
<div class="drop_option col-xs-12" *ngFor="let countries of countries; let i = index" (click)="fetchCountries(i,$event)">{{countries.CountryName}}</div>

Notice that you have used property countryName while performing unshift and CountryName in the template.

Please take advantage of typescript to identify such errors quickly

Create an interface/class

export interface CountryItem {
  idCity: number;
  CountryCode: string;
  CountryName: string;
}

and strongly type your variables

public countries: CountryItem[];

By doing this, errors such as these can be identified by the IDE's linter saving you time.

Stackblitz

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