考慮使用FormGroup
和Validators
實現這一目標。
import { NgModule, Component } from '@angular/core';
import { FormsModule, ReactiveFormsModule, FormGroup, FormControl, FormArray, FormBuilder, Validators } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';
@Component({
selector: 'my-app',
styles: [`
div {padding:5px; margin: 10px 0;}
.invalid {background-color: #ffd4d4;}
`],
template: `
<form [formGroup]="modelForm">
<div [formArrayName]="'items'" [class.invalid]="!modelForm.controls.selectedItems.valid">
<div *ngFor="let language of modelForm.controls.items.controls; let i = index;" [formGroup]="language">
<input type="checkbox" formControlName="checked" id="language_{{ language.controls.key.value }}">
<label attr.for="language_{{ language.controls.key.value }}">{{ language.controls.value.value }}</label>
</div>
</div>
<div [class.invalid]="!modelForm.controls.selectedItems.valid" *ngIf="!modelForm.controls.selectedItems.valid">
checkbox group is required!
</div>
<hr>
<pre>{{modelForm.controls.selectedItems.value | json}}</pre>
</form>
`
})
export class AppComponent {
modelForm:FormGroup;
items = [
{key: 'item1', value: 'value1'},
{key: 'item2', value: 'value2'},
{key: 'item3', value: 'value3'},
];
constructor(){
}
ngOnInit() {
let group = [];
this.items.forEach((l) => {
group.push(new FormGroup({
key: new FormControl(l.key),
value: new FormControl(l.value),
checked: new FormControl(false),
);
});
let formControlArray = new FormArray(group);
this.modelForm = new FormGroup({
items: formControlArray,
selectedItems: new FormControl(this.mapItems(formControlArray.value), Validators.required)
});
formControlArray.valueChanges.subscribe((v) => {
this.modelForm.controls.selectedItems.setValue(this.mapItems(v));
});
}
mapItems(items) {
let selectedItems = items.filter((l) => l.checked).map((l) => l.key);
return selectedItems.length ? selectedItems : null;
}
}
請參閱本plunker。
您沒有使用任何表單標籤,通過驗證,當你想驗證?像'點擊某個按鈕時應該說什麼都沒選擇' – Aravind
我想驗證何時沒有單個複選框被選中。例如:名稱:文本框,當用戶點擊它,但沒有輸入任何內容時,應顯示'名稱是必需的'。同樣去複選框 – user3431310