typescript 确认不适用于Angular 中的复选框

4si2a6ki  于 2023-02-17  发布在  TypeScript
关注(0)|答案(3)|浏览(147)

验证对复选框无效。
当复选框没有被选中时,表单正在被提交。也不显示错误。

    • HTML代码**
<form [formGroup]="feedbackFormWithArray" (ngSubmit)="submitData()">
  <label class="form-control-label"><span class="text-danger">*</span>Recommendation:</label>
  <div class="recommendation-div">
    <div class="rec-div" *ngFor="let recommendation of recommendations">
      <label class="container">{{recommendation.listTypeValueName}}
        <input formControlName="recommendation" type="checkbox" value="{{recommendation.listTypeValueId}}"
               [checked]="recommendation.selected" (change)="isAllSelected(recommendation)" />
        <span class="mark"></span>
      </label>
      <div *ngIf="(submitted && recommendation.invalid)">
        <small *ngIf="recommendation.errors?.required" class="text-danger">Please select recommendation</small>
      </div>
    </div>
  </div>
</form>
    • TS代码**
import { Validators } from '@angular/forms';

submitted : boolean  = false;

this.feedbackFormWithArray= this.fb.group({
  recommendation: ['', [Validators.required]]
});

submitData() {
  this.submitted = true;
}

get recommendation()
{
  return this.feedbackFormWithArray.get('recommendation');
}

怎么解决呢?谢谢!

mm5n2pyu

mm5n2pyu1#

我想在ts代码的第三行用feedbackFormWithArray替换feedbackForm

guicsvcw

guicsvcw2#

import { Validators } from '@angular/forms';

submitted : boolean  = false;
//in reactive form you should take care the form controller's name.
this.feedbackFormWithArray= this.fb.group({
  recommendation: ['', [Validators.required]]
});

submitData() {
  this.submitted = true;
}

get recommendation()
{
  return this.feedbackFormWithArray.get('recommendation');
}
2admgd59

2admgd593#

类Validators中有一个名为“requiredTrue”的静态属性。

this.feedbackFormWithArray= this.fb.group({
    recommendation: ['', [Validators.requiredTrue]]
});

@description要求控件值为true的验证器。此验证器通常用于必需的复选框。
您可以在此处查看更多信息https://angular.io/api/forms/Validators

相关问题