【问题标题】:angular reactive form doesn't support ngIf角度反应形式不支持 ngIf
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    hasInfo 更改时,您必须从 FormControls 添加/删除所需的验证器

    查看这篇文章 - Dynamically Add/Remove Validators in Angular Reactive Forms

    【讨论】:

      【解决方案3】:

      ngIf 只是阻止在html 文件中呈现您的div,它不会更改您对.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();
       }
      }
      

      根据this.hasInfo 的变化,调用这个updateValidations 函数。

      【讨论】:

        猜你喜欢
        • 2020-03-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-25
        • 2020-01-27
        • 2020-07-22
        • 1970-01-01
        相关资源
        最近更新 更多