简体   繁体   English

angular 反应形式不支持 ngIf

[英]angular reactive form doesn't support ngIf

I have a form group that I need to show one of the required inputs whit ngIf.我有一个表单组,我需要显示其中一个所需的输入 whit ngIf。 but even when this input does not exist, formcontrol check it and return form is not valid.但即使此输入不存在,formcontrol 也会对其进行检查并返回表单无效。 my code is like this html :我的代码是这样的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 : 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")
  }
}

if hasInfo is true that not to show firstName and lastName, my form should return valid but is always not valid如果 hasInfo 为真,不显示名字和姓氏,我的表单应该返回有效但始终无效

You can add conditional validators on form initialization.您可以在表单初始化时添加条件验证器。

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),
  });
}

ngIf just prevents rendering your div in the html file and it does not change your reactive form validation on your .ts file. ngIf只是阻止在html文件中呈现您的div ,并且它不会更改您对.ts文件的反应式表单验证。 for your purpose try this:为了你的目的,试试这个:

.ts: .ts:

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

updateValidations() {
 if( this.hasInfo ) {
  this.myForm.get("firstName").clearValidators();
  this.myForm.get("firstName").updateValueAndValidity();
  this.myForm.get("lastName").clearValidators();
  this.myForm.get("lastName").updateValueAndValidity();
 }
}

based on the this.hasInfo changes, call this updateValidations function.根据this.hasInfo的变化,调用这个updateValidations function。

You have to add/remove required validators from the FormControls when hasInfo is changedhasInfo更改时,您必须从 FormControls 添加/删除所需的验证器

Check this article - Dynamically Add/Remove Validators in Angular Reactive Forms检查这篇文章 - 在 Angular Reactive Forms 中动态添加/删除验证器

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM