角度反应形式不支持 ngIf

hel*_* rb 0 angular angular-reactive-forms

我有一个表单组,我需要显示 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>
Run Code Online (Sandbox Code Playgroud)

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")
  }
}
Run Code Online (Sandbox Code Playgroud)

如果 hasInfo 为 true 则不显示名字和姓氏,我的表单应返回有效但始终无效

Kam*_*tti 6

您可以在表单初始化时添加条件验证器。

ngOnInit() {
  if (accountResponse.length > 0) this.hasInfo= true;
  this.formBuilder();
}

formBuilder() {
  const required = this.hasInfo ? Validator.required : null;

  this.myForm= new FormGroup({
    mobile: new FormControl(null, Validator.required),
    firstName: new FormControl(null, required),
    lastName: new FormControl(null, required),
  });
}
Run Code Online (Sandbox Code Playgroud)