0

I try to write a method to delete and add item to array i need delete and add methods in a easy way because i am not familiar typescript

export class NgForComponent implements OnInit {

  Sayilar: number[];
  constructor() {
    this.Sayilar = [1, 2, 3, 4, 5];
   }

  ngOnInit() {
  }

}

html

        <div>
    <ul>
        <li *ngFor="let sayi of Sayilar">
          {{sayi}}
        </li>
    </ul>


    </div>

    <button >Delete</button>

3 Answers 3

2
 <li *ngFor="let sayi of Sayilar;let i = index">
          {{sayi}}
  <button (click)="deleteSayilar(i)">Delete</button>
 </li>


in typescript
deleteSayilar(i){
   this.Sayilar.splice(i,1);
}
Sign up to request clarification or add additional context in comments.

Comments

0

you need to place the delete within the ngFor inorder to get the clicked item, otherwise you would not know which item to delete , or change your interface in order to identify which item to be deleted.

<ul>
 <li *ngFor="let sayi of Sayilar">
          {{sayi}}
  <button (click)="delete(sayi)">Delete</button>
 </li>
</ul>

and then in TS,

delete(item : any){
   this.Sayilar.splice(item ,1);
}

8 Comments

Property 'remove' does not exist on type 'number[]' it says like this in TS
sure to set the compiler target to es6 in your tsconfig.
how i should add method after handle this problem
this.Sayilar = this.Sayilar.filter(e => e !== item)
how can it know the number will be add ?
|
0
<ul>
 <li *ngFor="let sayi of Sayilar">
          {{sayi}}
  <button (click)="delete(sayi)">Delete</button>
 </li>
</ul>

and your ts

delete(sayi){
this.Sayilar.filter(m => m !== sayi)
}

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.