Angular 4/5删除特定索引处的子元素

时间:2018-07-04 11:58:16

标签: angular

我有一个输入标签,其类型为“ number”。当我增加数字时,它会在div中插入/添加元素。现在,我要删除递减的最后一个元素。我该怎么办?

HTML代码:-

<input class="form-control" (click)="bedroomClick($event)" type="number" value="0" min="0">
<div class="row bedding-configuration" #bedding_config>
</div>

角度代码:-

previousBedRoomValue : number = 0;
bedroomClick(event) {

  if(event.target.value > this.previousBedRoomValue) {
    this.createBeddingConfigElements();
  }
  else {
    this.removeChildElement();
  }
  this.previousBedRoomValue = event.target.value;
}

createBeddingConfigElements()==>当输入计数器增加1时,将元素添加到div中。我要寻找的是当计数器减少1时删除最后一个元素。

3 个答案:

答案 0 :(得分:0)

您可以使用(input)指令捕获该事件,并推送或拼接div数组以获取正确数量的div。示例代码:

在component.html

<input type="number" value="0" min="0" (input)="addDiv()" [(ngModel)]="divsNumber">

<div *ngFor="let div of divs">div {{ div }}</div>

在component.ts

divs: Array<number> = [];

oldDivsNumber: number = 0;
divsNumber: number = 0;

addDiv = () => {
    if (this.divsNumber > this.oldDivsNumber) {
        this.divs.push(this.divs.length + 1);
    } else {
        this.divs.splice(this.divs.length - 1, 1);
    }
    this.oldDivsNumber = this.divsNumber;
}

您可以查看实时版本here

答案 1 :(得分:0)

为什么不只使用* ngIf来显示合适的时间

<input class="form-control" (click)="bedroomClick($event)" type="number" 
 value="0" min="0">

<div class="row bedding-configuration" #bedding_config *ngIf="showBeddingConfig">
</div>

在您的代码中,只需在bedroomClick()中将showBeddingConfig设置为true或false

答案 2 :(得分:0)

这就是我所做的。

component.ts中的代码=>

previousBedRoomValue : number = 0;

bedroomClick(event) {

  if(event.target.value > this.previousBedRoomValue ) {
    const control = <FormArray>this.addresidenceForm.controls['bedroom_config'];
    control.push(this.initBedroomConfiguration());
  }
  else {
    const control = <FormArray>this.addresidenceForm.controls['bedroom_config'];
    control.removeAt(event.target.value);
  }
  this.previousBedRoomValue = event.target.value;
}

.html文件中的代码。

<div class="col-xl-3 col-lg-3 col-md-3 col-sm-12 grid-margin">
  <div class="make-center mb-4 mt-4"></div>
  <input class="form-control" name="bedrooms" (click)="bedroomClick($event)" type="number" value="0" min="0">
  <label for="bedrooms">Bedrooms</label>
</div>

在单击事件中,它将在html页面中添加元素。

<div [hidden]= "i == 0" *ngFor = "let bedRoom of addresidenceForm['controls'].bedroom_config['controls']; let i = index" class="col-xl-6 col-lg-6 col-md-6 col-sm-12 grid-margin" >
  <div [formGroupName]="i" class="loop-beddingSection">
    <div class="row">
      <div class="col-xl-12 col-lg-12 col-md-12 col-sm-12 grid-margin">
        <label for="bedRoom"><sup class="orange-color">*</sup>Bedroom Name</label>
        <input class="form-control" type="text" name="bedroom_name" formControlName="bedroom_name">
      </div>
    </div>
  </div>
</div>

这是图片。

When number is 0

When number is 1

When number is 2