如何使用angular5在ngFor中绑定ngModel

时间:2019-01-30 11:00:58

标签: angular

任何人都可以帮助。我正在使用ngFor遍历数组,并且需要将标题绑定到ngModel。我输入了多少个标题,通过在ts文件中提供警报来测试了所有标题。它会给出一个空警报。

https://stackblitz.com/edit/angular-gzcy61?file=src%2Fapp%2Fapp.component.css

谢谢。

2 个答案:

答案 0 :(得分:0)

您没有将输入值存储在arrayOfObj;

只需单击“添加新标题按钮”,然后在<input>块中输入所需内容;使用以下HTML和TS替换stackblitz中的代码。

app.component.html

<input type="text" [(ngModel)]="head1" placeholder="enter text">
<ng-template #temp>
  <div *ngFor="let a of arrayOfObj">
    <input class="form-control" id="usr" placeholder="Enter heading..." [(ngModel)]="a.head2">
    <br>
    <br>

    <div class="col-md-2">
      <div class="btn-div">
        <div class="ss" (click)="onAddRow()" *ngIf="tmpo!=2;else tempo">Add new heading {{a.count}}</div>
      </div>
    </div>
  </div>
</ng-template>

<div class="col-md-2">
  <div class="btn-div">
    <div class="ss" (click)="onAddRow()" *ngIf="tmpo!=1;else temp">Add new heading</div>

    <input type="button" class="ss" value="submit" (click)="submit()">
  </div>
</div>

app.component.ts

    import { Component } from '@angular/core';
import { FormGroup, FormBuilder, Validators, FormControl, FormArray, NgForm } from '@angular/forms'

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  head1: string = '';
  head2: string = '';
  tmpo;
  count = 0;
  arrayOfObj: any[];

  constructor() {
    this.arrayOfObj = [];
  }

  onAddRow() {
    this.tmpo = 1;
    this.count++;
    this.arrayOfObj.push({ "count": this.count, "head2": "" });
  }

  onAddRow1() {
    // this.tmpo=2;
  }

  submit() {
    console.log(this.arrayOfObj);
    for (var i=0; i<this.arrayOfObj.length; i++){
      alert(this.arrayOfObj[i].head2);
    }
    //alert(this.head1)
    //alert(this.head2)
  }

}

答案 1 :(得分:0)

我认为您对绑定的工作原理和绑定方式有误解。

即使从结构上来说,就HTML而言,您做的也不正确,或者也许我只是不明白您要做什么。

就您而言,目前,该数组只是一个普通数组,您需要将其转换为对象数组,例如:

export class AppComponent {
  head1: string = '';
  head2: string = '';
  tmpo;
  count = 0;
  arrayOfObj: {head: string; position: number}[] = [];

onAddRow(){
this.tmpo=1;
this.count ++;
this.arrayOfObj.push({head: '', position: this.count});
}

那么您的HTML可以是:

<ng-template #temp>
  {{arrayOfObj|json}}
  <div *ngFor="let a of arrayOfObj; let i = index">
      <input class="form-control" id="usr" placeholder="Enter text..." [(ngModel)]="arrayOfObj[i].head"> 
        <br>
        <br>   

        <div class="col-md-2">
            <div class="btn-div">
              <div class="ss" (click)="onAddRow()" *ngIf="tmpo!=2;else tempo">Add new heading {{a.position}}</div>
            </div>
        </div>
  </div>
</ng-template>

ngModel确实可以在for循环中使用,但是您需要通过数组通过索引来引用它。