【问题标题】:Disable validation on selection of radio button in angular禁用对角度单选按钮选择的验证
【发布时间】:2021-07-23 13:28:08
【问题描述】:

我有一个包含 3 个字段的表单:类型(单选按钮)、名称和地点。 如果我从单选按钮中选择值“Y”,则应显示名称和地点。 如果我从单选按钮验证中选择值“N”,则不应显示位置。 请帮我实现功能。 工作堆栈闪电战: https://stackblitz.com/edit/angular-ivy-jzjh4j?file=src%2Fapp%2Fapp.component.ts

<input type="radio" formControlName="type" name="type" value="Y"/>
Yes
  <input type="radio" (change)="onChange($event)"
  formControlName="type" name="type" value="N"/>
No

  <small class="errormessage" *ngIf="submitted && addForm.controls.type.hasError('required')">
                            type is required
  </small>

TS

  onChange(evt)
  {
  var target = evt.target;
      if (target.checked) 
      {
        alert('hi');
        this.addForm.controls.place.valid === true;
      }
      else
      {
        this.addForm.controls.place.valid === false;
      }
}

【问题讨论】:

  • 不要手动设置valid状态...!如果一个控件的验证器是有效的,那么它就是有效的。如果您希望某个字段不出错,请删除使其出错的验证器。你能展示你的addForm初始化吗?
  • 感谢您的回复。先生,onsubmit - 我想显示所有字段的验证。但是当我将单选按钮选择为“N”时 - 我想删除“地点”的验证。我的工作 stackblitz 先生 - stackblitz.com/edit/…

标签: angular validation button radio


【解决方案1】:

实际上,您不应该将 reactiveForm 与模板表单混用。因此,如果您使用 fromGroup,请不要在 HTML 输入中使用 (change)。您必须订阅您的打字稿中的更改。 Also, your place input is required only if Y type is selected.因此,如果用户选择N,您必须删除required 验证器,这样您的表单才会有效。

这是您更新的 stackblitz:

  constructor(private formBuilder: FormBuilder) {}
  addForm: FormGroup;
  submitted = false;
  mySubscription: Subscription;

  ngOnInit(): void {
    this.addForm = this.formBuilder.group({
      type: ["", [Validators.required]],
      name: ["", [Validators.required]],
      place: ["", [Validators.required]]
    });
    this.mySubscription = this.addForm
                              .get('type')
                              .valueChanges
                              .subscribe(newValue => {
      if (newValue === 'N') {
        // place is not required anymore
        this.addForm.get('place').setValidators([]);
      } else {
        // place is required
        this.addForm.get('place').setValidators([Validators.required]);
      }
      // force valitators to be triggered, to update form validity.
      this.addForm.get('place').updateValueAndValidity();
    });
  }

  onSubmit() {
    this.submitted = true;
    if (this.addForm.invalid) {
      return;
    }

  }

  ngOnDestroy() {
    if (this.mySubscription) {
      this.mySubscription.unsubscribe();
    }
  }

【讨论】:

    猜你喜欢
    • 2018-07-13
    • 2016-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-02
    • 1970-01-01
    • 2019-09-20
    • 2020-11-01
    相关资源
    最近更新 更多