gpt4 book ai didi

angular - 验证复选框列表 Angular 2

转载 作者:太空狗 更新时间:2023-10-29 17:33:04 25 4
gpt4 key购买 nike

我有一个业务单位列表,这些业务单位在注册表单上呈现为复选框以及一个文本框字段,并且正在进行验证。

 <label for="inputFirstName" class="sr-only">First name</label>
<input type="text" formControlName="firstName" class="form-control" placeholder="First name">

<div class="checkbox" *ngFor="let bu of businessUnits">
<label><input type="checkbox" #instance value="{{bu.BuName}}" (click)="getCheckBoxValue(instance.checked, bu.BuName)">{{bu.BuName}}</label>
</div>

业务单位列表是从数据库表中检索的,并在加载表单时呈现

businessUnits: BusinessUnit[] = [];

在构造函数中,我像这样验证电子邮件

  "firstName": new FormControl('', [Validators.required]),

})

我将如何验证在页面加载时动态加载的复选框列表中至少有一个复选框被选中?

谢谢

最佳答案

让我们试试这个演示:https://stackblitz.com/edit/angular-custom-form-validation?file=app/app.component.ts

第二个参数将接受验证函数,就这样传递

this.fg = this.fb.group({
firstName: ['', [Validators.required]],
bUnits: this.fb.array(
this.businessUnits.map(() => this.fb.control('')),
CustomValidators.multipleCheckboxRequireOne
)
});

应用组件

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormArray, FormBuilder, Validators } from '@angular/forms'

import { CustomValidators } from './custom.validators';

@Component({
selector: 'app-root',
template: `
<form (ngSubmit)="onSubmit()" novalidate [formGroup]="fg">
<div><input type="text" formControlName="firstName" class="form-control" placeholder="First name"></div>
<div formArrayName="bUnits">
<div *ngFor="let unit of fg.controls.bUnits.controls; let i = index;">
<p>Unit {{ i + 1 }}</p>
<div>
<label>
<input type="checkbox" [formControlName]="i" [value]="businessUnits[i].value">
{{businessUnits[i].name}}
</label>
</div>
</div>
</div>

<button type="submit">Submit</button>
<p>Status {{ fg.valid }}</p>
</form>
`
})
export class AppComponent implements OnInit {
fg: FormGroup;
businessUnits: any[] = [];

constructor(private fb: FormBuilder) {}

ngOnInit() {
// do some stub to grab data
this.businessUnits = [
{name: 'BU 1', value: "1"},
{name: 'BU 2', value: "2"},
{name: 'BU 3', value: "3"}
];
this.fg = this.fb.group({
firstName: ['', [Validators.required]],
bUnits: this.fb.array(
this.businessUnits.map(() => this.fb.control('')),
CustomValidators.multipleCheckboxRequireOne
)
});

}

onSubmit() {
console.log(this.fg);
}
}

自定义验证器

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

export class CustomValidators {
static multipleCheckboxRequireOne(fa: FormArray) {
let valid = false;

for (let x = 0; x < fa.length; ++x) {
if (fa.at(x).value) {
valid = true;
break;
}
}
return valid ? null : {
multipleCheckboxRequireOne: true
};
}
}

关于angular - 验证复选框列表 Angular 2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42038099/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com