Angular 中的切换字段基于不同组件中的复选框的反应式表单(表单验证)

Toggle field in Angular Reactive form (form validation) based on a checkbox in a different component

我有一个复杂的表单,其中的字段基于不同组件(父组件)中的切换复选框。我需要验证表单,这意味着某些字段可能被禁用,而有些则没有。我需要它是动态的并根据复选框的 ticking/unticking 进行更改,而不是让它仅用于初始化。我试过很多例子都没有成功..

parent.component.html

<input type="checkbox" id="check" ng-model="checked" (click)='toggleCheckform()'>
<label for="check">Check me</label>

<mat-tab label="child">
   <child [isCheck]="toggleCheck" (messageToEmit)="getMessage($event)"></child>
</mat-tab>

parent.component.ts

export class ParentComponent {

    constructor() { }

    toggleCheck: boolean = false;

    ngOnInit() {
    }

    toggleCheckform() {
        this.toggleCheck = !this.toggleCheck;
    }
}

child.component.ts

export class ChildComponent {

  @Input() isCheck: boolean;

  testForm = this.fb.group({
    Field1: ['', Validators.required],
    Field2: ['', Validators.required]
  });

  get Field1() { return this.testForm.get('Field1'); }
  get Field2() { return this.testForm.get('Field2'); }

  if(isCheck){
    this.testForm.get('Field1').disable();
  }

  onSubmit() {
    // TODO: Use EventEmitter with form value
    console.warn(this.testForm.value);
  }

  constructor(private fb: FormBuilder) {
  }

  ngOnInit() {
  }

child.component.html

    <form [formGroup]="testForm" (ngSubmit)="onSubmit()">

    <div *ngIf="isCheck">
        <div class="form-group">
           <label for="Field1">Field1</label>
                <input type="text" class="form-control" id="Field1" formControlName="Field1">
        </div>
    </div>

    <div class="form-group">
       <label for="Field2">Field2</label>
           <input type="text" class="form-control" id="Field2" formControlName="Field2">
    </div>

    </form>

因此,基于父组件上的复选框,我希望能够 enable/disable 该表单字段进行验证。尝试了很多方法,该示例在初始化表单时有效,但在初始化之后无效。请帮忙。

您需要在输入中使用 "setter"

_isCheck:boolean
@Input() 
set isCheck(value)
{
  this._isCheck=true;
  const control=this.testForm.get('Field1')
  if(control)
  {
    if (value)
      control.enable();
    else
      control.disable();
   }
}

get isCheck()
{
    return this._isCheck
}

注意:当您禁用 FormControl 时,form.value 不包括值(您需要使用 form.getRawValue())此外,无论禁用的 formControl 的值是什么,表单都是有效的

一个stackblitz