在 angular 中禁用对单选按钮选择的验证

Disable validation on selection of radio button in angular

我有一个包含 3 个字段的表单:类型(单选按钮)、姓名和地点。 如果我 select 单选按钮验证的值 'Y' 应该显示名称和地点。 如果我从单选按钮验证中 select 值 '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;
      }
}

实际上,您不应该将 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();
    }
  }