【发布时间】:2018-12-25 09:32:39
【问题描述】:
我正在开发工作表,用户可以在工作表中输入他的爱好。我已经对 hobbyName formcontrol 应用了所需的验证,但是如果有多个爱好,我该如何验证应该是唯一的爱好名称。
下面是我的ts代码
import { Component,OnInit } from '@angular/core';
import { FormGroup,FormArray,FormBuilder,Validators } from "@angular/forms"
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
jobForm:FormGroup
constructor(private jobfb:FormBuilder){}
ngOnInit(){
this.jobForm = this.jobfb.group({
hobbies:this.jobfb.array([
this.createHobbyFormGroup()
])
})
}
addHobby(){
let hobbies = this.jobForm.controls.hobbies as FormArray;
hobbies.push(this.createHobbyFormGroup());
}
createHobbyFormGroup(){
return this.jobfb.group({
hobbyName:['',Validators.required]
});
}
}
下面是我的 HTML 代码
<button (click)="addHobby()">Add Hobby</button>
<table>
<tr [formGroup]="hobbyFG" *ngFor="let hobbyFG of jobForm.controls.hobbies.controls;">
<input formControlName="hobbyName"/>
</tr>
</table>
<button [disabled]="!jobForm.valid">Submit</button>
每当用户点击添加按钮时,新的 FormGroup 就会被添加到 FormArray 中。
我不知道如何验证应该是唯一的爱好名称?
请指导。
【问题讨论】:
标签: angular angular-reactive-forms