Select array to save

2

asked by anonymous 03.09.2018 / 16:38

1 answer

1

Posting the answer from stackblitz

app.module.ts

import { BrowserModule } from '@angular/platform-browser';

import { AppComponent } from './app.component';
import { HelloComponent } from './hello.component';

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
  @NgModule({
    declarations:[
      AppComponent,
      HelloComponent
    ],
    imports: [
      BrowserModule,
      CommonModule,
      ReactiveFormsModule,
      FormsModule,
    ],
    exports: [
    CommonModule,
    FormsModule,
    ReactiveFormsModule
  ],
    bootstrap:[ AppComponent ],

  })
  export class AppModule {}

app.component.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));
  }

  test(){
    console.log(this.selectedPermissoes())
  }

  }

app.component.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 (click)="test()">{{acessoForm.value | json}}</pre>
    
07.09.2018 / 17:12