В основном я не знаю, как обращаться с этой темой из *ngFor
, где есть флажок. Обычно я знаю, как это сделать с [(ngModel)]
, но я не знаю, как это сделать с реактивными формами.
Я хочу связать свой флажок в соответствии с тем, что у меня есть в переменной «aUsers», и отметить элементы, которые у меня есть в атрибуте «check».
что я должен делать?
this.ValidacionReunion = new FormGroup({
observaciones:new FormControl(null, []),
arrayElements: new FormControl.array([]) //this is the name of my checkboxlist
});
aUsers:any=
[
{
"name":"xds",
"userusuario":2,
"check":true
},
{
"name":"xdsx",
"iduser":2,
"check":false
}
]
. . .
<!-- obviously this is inside:<form [formGroup] = "ValidationReunion"> -->
<li class = "list-group-item waves-light" *ngFor = "let user of aUsers" >
<input type = "checkbox" formControlName = "user.check">{{user.name}} {{user.iduser}}
</li>
🤔 А знаете ли вы, что...
С помощью Angular можно легко интегрировать сторонние библиотеки и компоненты.
Вы должны создать массив FormControl следующим образом
компонент.ts
const control = this.aUsers.map(c=> new FormControl(c.check));
this.ValidacionReunion = this.fb.group({
observaciones:'',
arrayElements: this.fb.array(control)
});
компонент.html
<form [formGroup] = "ValidacionReunion">
<li formArrayName = "arrayElements" class = "list-group-item waves-light" *ngFor = "let control of ValidacionReunion.get('arrayElements').controls; let i = index">
<input type = "checkbox" [formControlName] = "i">{{aUsers[i].name}}
</li>
</form>
Пример:https://stackblitz.com/edit/angular-7gjkgr
В дочернем элементе управления установите значение имени элемента управления формы на user.check
.
Если ваше formControlName — «userCheck», то из класса компонента внутри вашей formGroup установите userCheck: user.check. Если это правда, это установит значение флажка в true.
В файле .ts создайте массив для ролей
Roles = [
{ id: true, description: 'W9' },
{ id: true', description: 'F9' },
{ id: true, description: 'other' },
];
this.customerForm = this.fb.group({
roles: this.fb.array([]),
});
функция проверки и снятия отметки
updateChkbxArray(chk, isChecked, key): void {
const chkArray = <FormArray>this.customerForm.get(key);
if (isChecked) {
// sometimes inserts values already included creating double records for the same values -hence the defence
if (chkArray.controls.findIndex(x => x.value === chk.id) === -1)
chkArray.push(new FormControl(chk.id));
} else {
const idx = chkArray.controls.findIndex(x => x.value === chk.id);
chkArray.removeAt(idx);
}
}
В настоящее время я показываю флажок в флажке углового материала. У вас может быть свой собственный флажок.
<mat-checkbox *ngFor = "let role of Roles" formArrayName = "roles"
(change) = "updateChkbxArray(role, $event.checked, 'roles')"
[value] = "role.id">{{role.description}}
</mat-checkbox>