Reputation: 57
Is it possible to bind more than one field in just one formControlName
, or do something similar to get the same result? I tried this but each select overwrites another.
Here a stackbliz exemple: https://stackblitz.com/edit/angular-tjgycw?file=src/app/app.component.html
Upvotes: 2
Views: 8500
Reputation: 5493
It is not possible to have form control names with shared model.
But in your case you can merge control models like this:
TS
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, FormControl } from '@angular/forms'
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
name = 'Angular';
acessoForm: FormGroup;
listaPermissoes: any[];
constructor(
private builder: FormBuilder,
) {
}
ngOnInit() {
this.listaPermissoes = [
{
"id": 2,
"nome": "grupo.perm.cadeira",
"permissoes": [
{
"id": 6,
"nome": "perm.cadastrarCadeira"
},
{
"id": 7,
"nome": "perm.alterarCadeira"
},
]
},
{
"id": 4,
"nome": "grupo.perm.mesa",
"permissoes": [
{
"id": 15,
"nome": "perm.cadastrarMesa"
},
{
"id": 16,
"nome": "perm.alterarMesa"
},
]
}]
this.acessoForm = this.builder.group(
this.listaPermissoes.map((item, index) => `permissoes-${index}`)
.reduce((pre, curr) => {
pre[curr] = [[]];
return pre; }, {}), {});
}
selectedPermissoes(){
return [].concat(...Object.values(this.acessoForm.value));
}
}
HTML
<form [formGroup]="acessoForm">
<div *ngFor="let listaPermissao of listaPermissoes; let i = index">
<div class="col-md-6">
<p>{{listaPermissao.nome}}</p>
</div>
<div class="col-md-6">
<select class="form-control" [formControlName]="'permissoes-'+i" multiple>
<option *ngFor="let permissao of listaPermissao.permissoes" [ngValue]="permissao">{{permissao.nome}}</option>
</select>
</div>
</div>
</form>
<pre>{{selectedPermissoes() | json}}</pre>
Upvotes: 1