Angular - Delete row from async pipe

3756 views angular
-1

The most common way to delete a row from an array is

this.countries.splice(pos, 1);

You have an array "countries" and you delete 1 element from the position "pos".

How about if we use async pipe?

countries$ = this.areasService.getCountries();


*ngFor="let c of (countries$ | async); let i=index"

How can I delete the element from the position "pos"? There is no array to delete from...

answered question

Hi again. You can't delete from an Observable, it has no buffer, nor does it keep track of what elements have been sent once it sends them. You could use a real list and get rid of ` asynPipe`, or use a filter based on some criteria.

thanks again...

you can have a dynamic refreshing of the elements inside *ngFor without using asyncPipe. Check my answer.

2 Answers

0

I would suggest subscribe the observable from the component itself , So you will get array of Countries

this.areasService.getCountries().subscribe((response)=>{
this.countries=response;
});

remove the async pipe , we have already subscribed the observable manually

*ngFor="let c of (countries); let i=index"

Now you can delete with an index

posted this
4

You can't delete from an Observable. It has no buffer, nor does it keep track of what elements have been sent once it sends them.

You could use an array, and the fact that angular detect changes on assignment :

countries = []

onInit

this.areasService.getCountries().subscribe( val=> this.countries =val);

html

*ngFor="let c of countries; let i=index"

Important:

when you splice, you should reassign this.countries in order to trigger change detection.

deleteEl(pos){
  this.countries.splice(pos, 1);
  this.countries = [...this.countries];
}

posted this

Have an answer?

JD

Please login first before posting an answer.

Ads

Categories