仅当第一个输入字段不为空时才在第二个输入字段中添加验证器

Zak*_*Zak 3 validation angular angular-reactive-forms

我正在使用 Angular Forms 开发一个表单,但我遇到了一个死胡同,我想仅当第一个输入字段不为空时才向第二个输入字段添加验证。

假设我有两个输入字段:姓名和年龄。因此,当在姓名中输入某些内容时,只有年龄才会被设置为必填。我在表单中使用 FormGroup 和 FormControl,这就是组件文件现在的样子,没有年龄验证器:

class Component implements OnChanges {
  @Input() name: string;
  @Input() age: string; 

  form = new FormGroup({
    name: new FormControl(''),
    age: new FormControl('')
  });

  ngOnChanges(changes) {

    if (changes.name?.currentValue !== changes.name?.previousValue) {
      this.setName(changes.name.currentValue);
    }

    if (changes.age?.currentValue !== changes.age?.previousValue) {
      this.setAge(changes.age.currentValue);
    }
  }

  setName(name) {

    this.form.patchValue({
      name,
    });

    if (name) {
      this.form.get('age').setValidators([
         Validators.required,
         this.form.get('age').validator
      ]);
    } 
    
  }

  setAge(age) {
    this.form.patchValue({
      age,
    });
  }

}
Run Code Online (Sandbox Code Playgroud)

这是模板:

<custom-input
      label="Name"
      placeholder="name"
      name="name"
      formControlName="name"
></custom-input>

<custom-input
      label="Age"
      placeholder="age"
      name="age"
      formControlName="age"
></custom-input>
Run Code Online (Sandbox Code Playgroud)

Nar*_*ali 5

可以用下面的方法哦!

监听您想要的表单字段的更改事件,然后检查该字段是否已填充,然后我们可以使用命令切换所需的内容,然后在setValidators更新后我们可以通过运行将重新验证表单来确保 updateValueAndValidity表单同步!

ts

import { Component, OnInit, OnDestroy } from '@angular/core';
import {
  FormBuilder,
  FormControl,
  FormGroup,
  Validators,
} from '@angular/forms';
import { Subscription } from 'rxjs';
import { pairwise, startWith } from 'rxjs/operators';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit, OnDestroy {
  name = 'Angular';

  form: FormGroup;
  subscription: Subscription;

  constructor(private formBuilder: FormBuilder) {}

  ngOnInit(): void {
    this.form = this.formBuilder.group({
      control1: [''],
      control2: [''],
    });
  }
  control1Change() {
    const control1 = <FormControl>this.form.get('control1');
    const control2 = <FormControl>this.form.get('control2');
    if (control1.value) {
      control2.setValidators([Validators.required]);
    } else {
      control2.setValidators(null);
    }

    control2.updateValueAndValidity();
  }
  control2Change() {
    const control1 = <FormControl>this.form.get('control1');
    const control2 = <FormControl>this.form.get('control2');
    if (control2.value) {
      control1.setValidators([Validators.required]);
    } else {
      control1.setValidators(null);
    }

    control1.updateValueAndValidity();
  }

  ngOnDestroy(): void {
    if (this.subscription) {
      this.subscription.unsubscribe();
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

超文本标记语言

<hello name="{{ name }}"></hello>
<form [formGroup]="form">
  <div style="margin-bottom: 1rem">
    <label for="control1">Make Field 2 required</label>
    <input
      id="control1"
      type="text"
      formControlName="control1"
      (change)="control1Change()"
    />
    <span
      *ngIf="form.controls.control1.hasError('required')"
      style="color: red; display: block; margin-top: 0.25rem;"
      >Field 2 is required</span
    >
  </div>
  <div style="margin-bottom: 1rem">
    <label for="control2"> Field 2 </label>
    <input
      id="control2"
      type="text"
      formControlName="control2"
      (change)="control2Change()"
    />
    <span
      *ngIf="form.controls.control2.hasError('required')"
      style="color: red; display: block; margin-top: 0.25rem;"
      >Field 2 is required</span
    >
  </div>
  <div>
    <button type="submit" [disabled]="!form.valid">
      Only enabled when form is valid
    </button>
  </div>
</form>
Run Code Online (Sandbox Code Playgroud)

分叉堆栈闪电战