обрабатывать флажок с "новым FormControl" - PullRequest
0 голосов
/ 27 января 2019

В принципе, я не знаю, как обрабатывать эту тему из *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>

Ответы [ 3 ]

0 голосов
/ 27 января 2019

В дочернем элементе управления установите значение имени элемента управления формы на user.check

. Если для вашего formControlName задано значение 'userCheck', то из класса компонента внутри вашей группы formGroup установите userCheck: user.check.Если это правда, для флажка будет установлено значение true.

0 голосов
/ 28 января 2019

В .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>
0 голосов
/ 27 января 2019

Вы должны создать массив FormControl следующим образом

component.ts

const control = this.aUsers.map(c=> new FormControl(c.check));

this.ValidacionReunion = this.fb.group({
  observaciones:'',
  arrayElements: this.fb.array(control)

});

component.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

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...