Angular 2我不知道如何删除推送对象的一行

时间:2016-03-16 14:39:11

标签: arrays typescript angular

首先让我清楚我的问题/问题:

首先它是这样的:https://www.dropbox.com/s/92z2oe7f4w5x2b5/conditions.jpg?dl=0这里它删除了我的案例条件中最后创建的对象。

但我想分别删除每个条件,请看每行旁边的红色框:https://www.dropbox.com/s/ptwq6sk6da4p21k/new.jpg?dl=0

row.names

在上面的代码中,我将使用条件对象导入getConditions。有没有人知道我是怎么做的,处理这个问题的最佳方法是什么?

我想

import {Component, OnInit, DynamicComponentLoader, Input} from 'angular2/core';
import {Condition}    from './condition';

import {DateCondition}    from './datecondition.component';
import {StringCondition}    from './stringcondition.component';
import {SelectCondition}    from './selectcondition.component';
import {ConditionDetailComponent}    from './conditiondetail.component';

import {ConditionService} from './condition.service'

@Component({
    selector: 'condition-builder',
    templateUrl: 'app/conditionbuilder.component.html',
    directives: [ConditionDetailComponent],
})

export class ConditionBuilderComponent implements OnInit {
    conditions: Condition[] = [];
    catalog: Condition[] = [];

constructor(public _conditionService: ConditionService) { }

getConditions() {
    this._conditionService.getConditions().then(conditions => this.catalog = conditions);
}

ngOnInit() {
    this.getConditions();
}

onChange(conditionsIndex, selectedCondition:string): void {
    this.conditions[conditionsIndex] = this.catalog.find(condition => condition.name == selectedCondition);
}

newCondition() {
    this.conditions.push(this.catalog[0]);
}

deleteCondition() {
    this.conditions.pop();
}
}

就像这是代码构建,我希望你很清楚帮助我。 deleteCondition方法如何知道他需要删除哪一行以及如何从页面上方的代码中删除它?

我希望有人可以帮助我!!

1 个答案:

答案 0 :(得分:10)

您可以将列表提供给子组件并从中删除当前元素。这样就可以删除循环中的相关组件。

  • 主要成分:

    @Component({
      selector: 'my-app',
      template: `
        <div *ngFor="#elt of data">
          <my-component [elt]="elt" [data]="data"></my-component>
        </div>
      `,
      directives: [MyComponent]
    })
    export class AppComponent {
      constructor() {
        this.data = [
          {name: 'name1'},
          {name: 'name2'},
          {name: 'name3'},
          {name: 'name4'}
        ];
      }
    }
    
  • 子组件:

    @Component({
      selector: 'my-component',
      template: `
        <div>{{elt.name}} <span (click)="delete()">X</span></div>
      `
    })
    export class MyComponent {
      @Input()
      elt: any;
    
      @Input()
      data: any[];
    
      delete() {
        var index = this.data.indexOf(this.elt);
        this.data.splice(index, 1);
      }
    }
    

请参阅此plunkr:https://plnkr.co/edit/o5O0Rr?p=preview