我使用的是角2.4,需要使用「FormArray」製作動態表單,但HTML根本不能識別我的數組。 我有這樣的錯誤: 造成的:無法找到名稱對照: '0'如何在角度使用FormArray 2.4
TS文件:
import { Component } from '@angular/core';
import { FormGroup, FormControl, Validators, FormArray } from '@angular/forms';
@Component({
selector: 'my-formstwo',
templateUrl: "app/fromstesttwo/fromstesttwo.component.html",
})
export class FromstesttwoComponent {
myForm: FormGroup;
constructor(){
this.myForm = new FormGroup({
'dataforms': new FormGroup({
'username': new FormControl('sh', [Validators.required,Validators.minLength(3)]),
'email': new FormControl('',
[
Validators.required,
Validators.pattern("[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?")
])
}),
'password': new FormControl('', Validators.required),
'gender': new FormControl('Fmale',Validators.required),
'hobys': new FormArray([
new FormControl('SF')
])
});
}
get hobyss(): FormArray { return this.myForm.get('hobys') as FormArray; }
addHobys() {
this.hobyss.push(new FormControl());
}
genders:Array<string> = [
'Male',
'Fmale'
]
onSubmit(){
console.log(this.myForm);
}
}
HTML文件:
<div class="clearfix"> </div>
<p> </p>
<form [formGroup]="myForm" (ngSubmit)="onSubmit()">
<div formGroupName="dataforms">
<div class="form-group">
<label for="exampleInputEmail1">Username</label>
<input
type="username"
class="form-control"
id="exampleInputEmail1"
placeholder="Username"
formControlName="username">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input
type="email"
class="form-control"
id="exampleInputEmail1"
placeholder="Email"
formControlName="email">
<div *ngIf="!myForm.controls.dataforms.controls.email.valid">
email inValid
</div>
</div>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input
type="password"
class="form-control"
id="exampleInputPassword1"
placeholder="Password"
formControlName="password">
</div>
<div class="form-group">
<div class="radiobottom" *ngFor="let g of genders">
<input type="radio" name="gender" [value]="g" formControlName="gender">
{{g}}
</div>
</div>
<div FormArrayName="hobys">
<div class="form-group" *ngFor="let h of myForm.controls.hobys.controls; let i=index">
<p> </p>
<input
type="text"
class="form-control"
formControlName="{{ i }}">
</div>
</div>
<button type="button" class="btn btn-primary" (click)="addHobys()">Hoby</button>
<button type="submit" class="btn btn-default" [disabled]="!myForm.valid">Submit</button>
</form>
我的錯誤控制檯:
EXCEPTION: Error in app/fromstesttwo/fromstesttwo.component.html:53:10 caused by: Cannot find control with name: '0'