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

时间:2017-08-25 09:05:35

标签: javascript angular

大家好我在我的项目中使用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>

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

  

错误错误:找不到路径控件:&#39; myArray - &gt; 1 - &gt;

1 个答案:

答案 0 :(得分:0)

  1. 不要使用AngularJS

  2. 来操作DOM
  3. 在控制器中创建输入数组

  4. $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">
    

    Example