【问题标题】:How to remove an element based on some property using typescript in angular如何使用 angular 中的 typescript 删除基于某些属性的元素
【发布时间】:2018-01-26 06:22:13
【问题描述】:

我想根据它的任何属性从数组中删除一个元素,该属性可以是它的键、名称或电子邮件或其他可能的东西。

HTML

<tr *ngFor="let person of persons;" (click)="remove(person.key)">
  <td>{{person.key}}</td>
  <td>{{person.name}}</td>
  <td>{{person.email}}</td>
</tr>

打字稿

persons = [
{ key: 1, name: 'Mr.sohail', email: 'sohail@tee.com' },
{ key: 2, name: 'Mr.Farhan', email: 'farhan@tee.com' },
{ key: 3, name: 'Mr.Fida', email: 'fida@tee.com' },
{ key: 4, name: 'Mr.Liaqat', email: 'liaqat@tee.com' },
{ key: 5, name: 'Mr.Abdullah', email: 'abdullah@tee.com' },
{ key: 6, name: 'Mr.Ubaid', email: 'ubaid@tee.com' },
{ key: 7, name: 'Mr.Wasif', email: 'wasif@tee.com' }
]

remove 方法 根据 key 属性删除元素 但它会根据索引删除。

remove(key) {
console.log(key);
this.data.persons.splice(key, 1);
}

请让我知道应用所需的更改

谢谢

【问题讨论】:

  • 您的问题是什么?你已经做对了
  • 我想在属性基础上删除它,而不是在索引基础上
  • 我可以清楚地看到key 是元素的独特属性。我仍然想知道,你看到这个答案有什么问题..
  • 现在我已经更新了我的问题
  • 我的问题的标题已经表明我需要在某些属性基础上删除它,而不是索引基础

标签: angular typescript


【解决方案1】:
 removeByPropertyName(propertyName: string, value: any): void {
    let indexToRemove = persons.findIndex(p => p[propertyName] === value);
    if (indexToRemove !== -1)
        this.remove(indexToRemove);
    else
        console.log('Not found!');
 }

要按键删除,可以使用方法 as

removeByPropertyName('key', 10);

按名称删除,

removeByPropertyName('name', 'somename');

【讨论】:

    【解决方案2】:

    因为您想从基于动态key 的集合中删除元素(假设它应该是唯一的)。您可以考虑为您的 remove 函数传递两个参数,objectpropName

    <tr *ngFor="let person of persons;" (click)="remove(person,'key')">
      <td>{{person.key}}</td>
      <td>{{person.name}}</td>
      <td>{{person.email}}</td>
    </tr>
    
    remove(person, propName){
       this.persons = this.persons.filter(p => p[propName] !== person[propName])
    }
    

    Demo Here

    【讨论】:

      【解决方案3】:

      使用filter 函数。另外,我认为应该是this.persons 而不是this.data.persons

      remove(key) {
        console.log(key);
        this.persons= this.persons.filter(obj => obj.key !== key);
      
      }
      

      【讨论】:

        【解决方案4】:

        使用过滤器怎么样?

        remove(key) {
        console.log(key);
        this.persons = this.persons.filter(t=>t.key != key);
        }
        

        【讨论】:

          【解决方案5】:

          根据您的用例,如果您尝试在单击某个项目时删除它,您可以(并且应该)使用索引。我认为没有理由使用财产。

          以下是我如何根据索引删除项目:

          <tr *ngFor="let person of persons; index as i" (click)="remove(i)">
            <td>{{person.key}}</td>
            <td>{{person.name}}</td>
            <td>{{person.email}}</td>
          </tr>
          
          remove(index) {
              this.data.persons.splice(index, 1);
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2022-10-31
            • 2021-03-28
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多