如何使用 angular2 动态添加文本字段



大家好,我在我的项目中使用 angular2,我正在尝试动态添加输入文本,它的工作原理是这样的代码:

TS:

initArray() {
return  this._fb.group({  
title: ['', Validators.required]
})
}
addArray() {
const control = <FormArray>this.myForm.controls['myArray'];
//this.myGroupName.push(newName);
control.push(this.initArray());
}

.HTML:

<div formArrayName="myArray">
<div *ngFor="let myGroup of myForm.controls.myArray.controls; let i=index">
<div [formGroupName]="i">
<span *ngIf="myForm.controls.myArray.controls.length > 1" (click)="removeDataKey(i)" class="glyphicon glyphicon-remove pull-right" style="z-index:33;cursor: pointer">
</span>
<!--[formGroupName]="myGroupName[i]"-->
<div [formGroupName]="myGroupName[i]">
<div class="inner-addon left-addon ">
<i class="glyphicon  marker" style="border: 5px solid #FED141"></i>
<input type="text" style="width:50% !important" formControlName="title" class="form-control" placeholder="Exemple : Maarif, Grand Casablanca" name="Location" Googleplace (setAddress)="getAddressOnChange($event,LocationCtrl)">
<br/>
</div>
</div>
<!--[formGroupName]="myGroupName[i]"-->
</div>
<!--[formGroupName]="i" -->
</div>
</div>
<br/>
<a (click)="addArray()" style="cursor: pointer">+ add text Field</a>

当我添加新的文本字段时,它给了我一个错误,有什么建议吗?

错误

错误:找不到具有路径的控件:"myArray -> 1 ->

  1. 不要用 AngularJS 操作 DOM

  2. 在控制器中创建输入数组

$scope.inputs = [];
$scope.inputs.push({ id: 'input1', value: 'input1' });
$scope.inputs.push({ id: 'input2', value: 'input2' });
$scope.inputs.push({ id: 'input2', value: 'input2' });
<input ng-repeat="input in inputs" ng-model="input.value">

最新更新