2

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

1 Answer 1

1

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.