【问题标题】:Remove button on list item/array in Angular 12删除Angular 12中列表项/数组上的按钮
【发布时间】:2021-09-29 21:53:17
【问题描述】:

我正在尝试使用单击按钮删除列表项,尝试了各种选项,但似乎不起作用。希望你能帮我解决这个问题。

单击时我想从我的用户数组中删除一个列表项。我会将 Typescript 代码与 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>

【问题讨论】:

  • 嗨,userDeleted 是一个发射器,而不是您尝试更改值的数组。您应该 emit() 按钮被点击和被点击的项目,并让 父组件(拥有整个数组)移除被点击的项目。
  • 考虑将所有数据封装在&lt;tr&gt;标签内并循环遍历数据,而不是使用scope='row'

标签: javascript html angular typescript


【解决方案1】:

正如@Priscila 回答的那样,当单击按钮时,您应该只发出动作并让父组件控制相应的方法,即删除或添加。

因为这样,数据很容易被操作和处理组件的生命周期。

永远不要在应用程序上运行死胡同。

快乐编码:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-01-20
    • 2016-01-03
    • 1970-01-01
    • 1970-01-01
    • 2016-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多