如何在 angular 中的 formArray 中为表单控件设置验证器

How to set validators for a form control inside a formArray in angular

我正在尝试在 angular 中的 formArray 中设置一个验证器,但我不知道如何创建它,我的 formGroup 是

 itemsForm = this.fb.group({
    array: this.fb.array([this.fb.control(['']).setValidators(Validators.required)]),
  });

我尝试在数组中设置验证器,但在 html 它允许我添加另一个字段而不验证它是否为空我的代码是这样的:

HTML

<section [formGroup]="itemsForm" class="m-5">
  <section
    formArrayName="array"
    class="justify-content-center d-flex flex-wrap"
  >
    <div>
      <section class="d-flex flex-wrap">
        <div class="">
          <h4>Items Selected</h4>
        </div>
        <div class="">
          <button class="btn btn-primary" (click)="addItem()">Add Item</button>
        </div>
      </section>

      <section class="d-flex flex-column">
        <div
          class="form-group d-flex flex-row align-items-center"
          *ngFor="let item of itemsArray.controls; let index = index"
        >
          <h2 class="mr-2">item</h2>
          <input
            type="text"
            [formControlName]="index"
            class="form-control"
            [ngClass]="{
              'is-invalid': item.touched  && !item.valid
            }"
          />
        </div>
      </section>
    </div>
  </section>
</section>

TS

  @Input() defaultOption: string = '';
  @Input() optionsList: Array<string> = [];
  @Output() optionSelected = new EventEmitter<string>();

  selected: string = '';
  constructor(private fb: FormBuilder) {}
  itemsForm = this.fb.group({
    array: this.fb.array([this.fb.control(['']).setValidators(Validators.required)]),
  });


  get itemsArray(){
    return this.itemsForm.get('array') as FormArray
  }

  ngOnInit(): void {}

  updateSelection() {
    this.optionSelected.emit(this.selected);
  }
  addItem() {
    this.itemsArray.push(this.fb.control(''));
  }

试试这个...

  constructor(private fb: FormBuilder) {}
  itemsForm = this.fb.group({
    array: this.fb.array([this._createFormArrayControls()]),
  });


  get itemsArray(){
    return this.itemsForm.get('array') as FormArray
  }

  ngOnInit(): void {}

  private _createFormArrayControls(): FormControl{
   return this.fb.control('', Validators.required)
  }

将来,如果您需要将表单数组初始化为某个基于数组的默认值,您可以将 FormControl 转换为 FormGroup 并执行此操作:

@Input() set items(value: Item[]) {
    itemsForm = this.fb.group({
    array: this.fb.array(value.map(i => this._createFormArrayGroup(i))),
  });
};
  constructor(private fb: FormBuilder) {}   
    
  ngOnInit(): void {}

  private _createFormArrayGroup(item?: Item): FormGroup{   
   return this.fb.group({
    myItem: this.fb.control(item.Value, Validators.required)
   })
  }