我使用的是angular 7动态表单,在该表单中我从@ angular / forms导入FormBuilder和FormArray。我面临一些我无法弄清楚我在角度上是新的错误
import { Component } from '@angular/core';
import {FormBuilder, FormArray} from '@angular/forms';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(private fb:FormBuilder){}
users = this.fb.group({
user_fname:this.fb.array([]),
user_lname:this.fb.array([]),
user_conatact:this.fb.array([]),
user_email:this.fb.array([])
});
get UserFirstName()
{
return this.users.get('user_fname') as FormArray;
}
get UserLastName()
{
return this.users.get('user_lname') as FormArray;
}
get UserContact()
{
return this.users.get('user_conatact') as FormArray;
}
get UserEmail()
{
return this.users.get('user_email') as FormArray;
}
addNewUserRow()
{
this.UserFirstName.push(this.fb.control(''));
this.UserLastName.push(this.fb.control(''));
this.UserEmail.push(this.fb.control(''));
this.UserContact.push(this.fb.control(''));
}
}
和我的组件html代码是
<div class="container">
<h1>User Registeration Form</h1>
<hr />
{{users.value | json}}
<form [formGroup]="users">
<div class="row">
<div class="col-md-3">
<div class="form-group">
<label for="first-name">First Name</label>
<input type="text" class="form-control">
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label for="last-name">Last Name</label>
<input type="text" class="form-control">
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label for="last-name">Contact No</label>
<input type="text" class="form-control">
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label for="last-name">Email Address</label>
<input type="text" class="form-control">
</div>
</div>
<div formControlArray="user_fname" *ngFor="let fname of UserFirstName.controls; let i=index;" class="col-md-3">
<div class="form-group">
<label for="">First Name</label>
<input type="text" class="form-control" formControlName="i">
</div>
</div>
<div formControlArray="user_lname" *ngFor="let fname of UserLastName.controls; let i=index;" class="col-md-3">
<div class="form-group">
<label for="last-name">Last Name</label>
<input type="text" class="form-control">
</div>
</div>
<div formControlArray="user_contact" *ngFor="let fname of UserContact.controls; let i=index;" class="col-md-3">
<div class="form-group">
<label for="last-name">Contact No</label>
<input type="text" class="form-control">
</div>
</div>
<div formControlArray="user_email" *ngFor="let fname of UserEmail.controls; let i=index;" class="col-md-3">
<div class="form-group">
<label for="last-name">Email Address</label>
<input type="text" class="form-control">
</div>
</div>
</div>
</form>
添加新行
并且它给我以下错误AppComponent.html:40错误错误:找不到名称为'i'
的控件这里是一个小demo
,您在其中有一个可见的表单可以添加第一个用户,然后单击添加按钮以添加更多行以添加更多用户。很抱歉,您可以根据需要添加简单的样式。