0

I am trying to delete dynamic <tr> using Angular. But my test was not successful.
I can't find what is the error for this.

page.component.html

<tr *ngFor="let row of selectedOptions$ | async; let i =index;">
   <td>{{ row.code.value }}</td>
   <td>{{ row.desc.value }}</td>
   <td>{{ row.amount }}</td>
   <td style="float: right">
      <button type="button" class="btn btn-secondary btn-sm waves-effect waves-light" data-toggle="modal" data-target="#formemodal"><i class="fa fa-edit"></i> Edit</button>
      <button type="button" class="btn btn btn-sm waves-effect waves-light delete"><i class="fa fa-bitbucket" (click)="deleteRow(i)">Delete</i></button>
   </td>
</tr>

page.component.ts

selectedOptions$ = new BehaviorSubject([]);
constructor() { }

ngOnInit(){
}

deleteRow(index) {  
  if(this.selectedOptions$.value.length ==1) {
      return false;  
  } else {
      this.selectedOptions$.value.splice(index, 1); 
  }  
}

2 Answers 2

1

Your subject is not updated.

Try changing this

this.selectedOptions$.value.splice(index, 1); 

With

const newContent = this.selectedOptions$.value.splice(index, 1); 
this.selectedOptions$.next(newContent);
Sign up to request clarification or add additional context in comments.

Comments

1

You should not directly act on the BehaviorSubject value property, as it is an anti-pattern.
Instead, next() a new array.

const slicedArray = this.yourArray.slice(1);
this.selectedOptions$.next(slicedArray);

As you can see I've also used slice, to produce a new array reference, instead of modifying the old one.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.