export interface SelectedListItem { value: string; text: string; checked: boolean; }
export class AppComponent implements OnInit {
selectedListItem: SelectedListItem[] = [];
ngOnInit(): void {
// میتوان این مقادیر را از یک
// api
// دریافت کرد
this.selectedListItem.push({ value: '1', text: 'Friday', checked: false });
this.selectedListItem.push({ value: '2', text: 'Monday', checked: false });
this.selectedListItem.push({ value: '3', text: 'Saturday', checked: false });
this.selectedListItem.push({ value: '4', text: 'Sunday', checked: false });
this.selectedListItem.push({ value: '5', text: 'Thursday', checked: false });
this.selectedListItem.push({ value: '6', text: 'Tuesday', checked: false });
this.selectedListItem.push({ value: '7', text: 'Wednesday', checked: false });
}
save(form, evetn: Event) {
if (form.valid && this.isValidated()) {
alert('valid');
} else {
alert('invalid');
}
}
isValidated () {
const selected = this.selectedListItem.filter(x => x.checked === true);
if (selected && selected.length > 0) {
return true;
} else {
return false;
}
}
}
<form #form="ngForm" novalidate (submit)="save(form,$event)"> <div *ngFor="let item of selectedListItem"> <input type="checkbox" [(ngModel)]="item.checked" name="off"> <label> {{item.text}} </label> </div> <p [hidden]=" !form.submitted || isValidated()"> This field is required </p> <div> <input type="submit"> </div> </form>