Angular 7表单控件中的复选框,其中选中了最多3个复选框

我的.ts文件代码是

orders = [
    {id: 1, name: "order 1"},
    {id: 2, name: "order 2"},
    {id: 3, name: "order 3"},
    {id: 4, name: "order 4"},
  ];

  constructor(private _formBuilder: FormBuilder){
    const controlArray = this.orders.map(c => new FormControl(false));
    controlArray[0].setValue(true);

    this.form = this._formBuilder.group({
      orders: new FormArray(controlArray),
    });


  }

  onSubmit(): void {
        const selectedOrderIds = this.form.value.orders
      .map((v, i) => v ? this.orders[i].id : null)
      .filter(v => v !== null);

    console.log(selectedOrderIds);
  }

我的HTML文件是

<form [formGroup]="form" (ngSubmit)="onSubmit()">
    <label formArrayName="orders" *ngFor="let order of form.controls.orders.controls; let i = index">
    <input type="checkbox" [formControlName]="i">
    {{orders[i].name}}
  </label>
  <button type="submit">submit</button>
</form>

我需要复选框的必填验证,并且要选择的最小复选框为1,最大为3。 如何在Angular 7中实现这一目标?

评论