【发布时间】:2020-08-15 10:42:33
【问题描述】:
我有一个表单组,我需要显示所需的输入之一 whit ngIf。但即使此输入不存在,formcontrol 也会对其进行检查并返回表单无效。我的代码是这样的 html:
<form [formGroup]="myForm" (ngSubmit)="onSubmit()">
<label>mobile</label>
<input type="text" formControlName="mobile" />
<div *ngIf="!hasInfo">
<label>firstName</label>
<input type="text" formControlName="firstName" />
<label>lastName</label>
<input type="text" formControlName="lastName" />
</div>
<button type="submit">Submit</button>
</form>
ts:
constructor(){
this.formBuilder();
}
ngOnInit() {
if (accountResponse.length > 0) this.hasInfo= true;
}
formBuilder() {
this.myForm= new FormGroup({
mobile: new FormControl(null, Validator.required()),
firstName: new FormControl(null, Validator.required()),
lastName: new FormControl(null, Validator.required()),
});
}
onSubmit(){
if(this.myForm.valid){
console.log("valid")
}else{
console.log("not valid")
}
}
如果 hasInfo 为真,不显示名字和姓氏,我的表单应该返回有效但始终无效
【问题讨论】:
-
表单模型是抽象的,required的意思是required。您希望有条件地要求它,因此您需要一个实现此条件的自定义验证器。
-
当您在组件中声明表单字段时,Angular 正在寻找它的模板。所以仅在模板上使用
*ngIf是不够的。我会在这里选择不同的方法并尝试以编程方式添加或删除控件 -
我通过自定义条件检查了我的表单,它的工作,感谢您的帮助@Ingo Bürk
标签: angular angular-reactive-forms