[英]how to bind ngModel in ngFor using angular5
Cananyone請幫忙。 我正在使用ngFor遍歷數組,並且需要將標題綁定到ngModel。 我輸入了多少個標題,通過在ts文件中提供警報來測試了所有標題。 它給出一個空警報。
https://stackblitz.com/edit/angular-gzcy61?file=src%2Fapp%2Fapp.component.css
提前致謝。
您沒有將輸入值存儲在arrayOfObj中;
只需單擊“添加新標題按鈕”,然后在<input>
塊中<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)
}
}
我認為您對綁定的工作方式以及綁定的方式誤解了。
即使從結構上來講,您在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循環中使用,但是您需要通過數組通過索引來引用它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.