Remove button on list item/array in Angular 12

Viewed 362

I'm trying to remove a list item with the click button, tried various options but it seems to not work. Hope you can help me out with this.

On click i want to remove a list item from my users array. I will link the Typescript code alongside with the HTML.

//Typescript code
import { UsersService } from './../users.service';
import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { Iuser } from '../interfaces/iuser';

@Component({
  selector: 'tr[app-table-row]',
  templateUrl: './table-row.component.html',
  styleUrls: ['./table-row.component.css']
})
export class TableRowComponent implements OnInit {

  @Input() item!: Iuser;
  @Output() userDeleted = new EventEmitter();
  

removeUser(item: any) {
    this.userDeleted.emit(item);
  }

  constructor() {}
  ngOnInit(): void {}
}
<th scope="row">{{item.id}}</th>
<td>{{item.name}}</td>
<td>{{item.lastname}}</td>
<td>{{item.city}}</td>
<td> <button class="btn btn-sm" (click)="removeUser(item)">remove</button></td>

1 Answers

As @Priscila answered, when the button is clicked, you should only emit the action and let the parent component control the respective method i.e. delete or add.

Because that way, it will be easy for the data to be manipulated and handle the component's lifecycle.

Never keep the dead ends running on the app.

Happy Coding :)

Related