Angular 6: Selected does not work with [(ngModel)] and (ngSubmit)="onsubmit()

Asked

Viewed 674 times

3

I receive the Customer class in my form

import { NgSelectOption } from '@angular/forms';

export class Cliente {
    nome: string = '';
    carros: any [] = [
      { id: 1, modelo: 'Gol',selected:false },
      { id: 2, modelo: 'Saveiro',selected:true },

    ];

  }

 ngOnInit() {

    this.cliente = new Cliente();
  }

I want to leave the option preset when the value Selected is true.

<select [(ngModel)]="cliente.carros" name="cliente.carros" >
  <option *ngFor="let c of cliente.carros"  [selected]="c.selected" [value]="c.id">
    {{c.modelo}}
  </option>
</select>

But when I do this without the name="" property the value is not passed to the Submit in my form

Follow below the image like this now. inserir a descrição da imagem aqui

inserir a descrição da imagem aqui

Follow the project link https://stackblitz.com/github/CristovaoTorres/AngularCrudTest

  • It’s kinda weird, you’re trying to throw the value back into cliente.carros, tries to point out the [(ngModel)]= for another variable, for example carrosSelecionados

6 answers

2


I created a function to select the Selected item (maybe it’s not the right one)

  SelecionarCarroSelect(){
this.cliente.carros.forEach((item, index) => { 
  if(item.selected)
  this.carro = item.modelo;
});

}

and html

   <select [(ngModel)]="carro" name="cliente.carros" >
  <option *ngFor="let c of cliente.carros"  >
     {{c.modelo}}
   </option> 
 </select>

0

<form (ngSubmit)="onSubmit()">

  <div class="form-group">
    <label for="nome">Nome</label>
    <!-- <input type="text" class="form-control" name="name" id="nome" [(ngModel)]="cliente.nome"> -->
  </div>

  <div class="form-group">
    <label for="tipo">Tipo</label>
    <select>
      <ng-container *ngFor="let carro of cliente.carros"> 
         {{carro.nome}}
      <ng-container *ngIf="carro.selected">
         <option [value]="carro.id" [selected] >
           {{carro.modelo}}
        </option>
      </ng-container>
      <ng-container *ngIf="!carro.selected">
         <option [value]="carro.id">
           {{carro.modelo}}
        </option>
      </ng-container>
      </ng-container>
    </select>
    </div>
  <input type="submit" class="btn btn-primary mt-4" value="Salvar">
  <a href="#" class="btn btn-secondary mt-4 ml-2">Cancelar</a>

</form>
  • Thank you for the answer, unfortunately it did not work, I inserted an image in the question

  • when you click on the arrow, the options appear correctly?

  • If possible Specify the element referring to the <select> and send an image

  • I changed the question with the img

  • edited, see if it now works

  • It didn’t work, I uploaded my project into Git https://stackblitz.com/github/CristovaoTorres/AngularCrudTest

Show 2 more comments

0

I use the [checked] inside the tag to leave it preselected (this is for radio button). Example:

<label for="permissoes">Funcionalidades & Permissões</label>
            <div class="row">
              <div class="col">
                <div class="form-check " *ngFor="let pp of perfilPermissoes; let x = index">
                  <input class="form-check-input" type="hidden">{{ pp.nome_funcionalidade }}
                  <div class="float-right">
                    Sim<input class="form-check-inline ml-2 perm" type="radio" name="optPermissao_{{pp.id_perfil_permissao}}" value="1" id="checkinfo_{{pp.id_perfil_permissao}}_1" [checked]="pp.permissao == 1">
                    Não<input class="form-check-inline ml-2 perm" type="radio" name="optPermissao_{{pp.id_perfil_permissao}}" value="0" id="checkinfo_{{pp.id_perfil_permissao}}_0" [checked]="pp.permissao == 0">
                  </div>
                </div>
              </div>
            </div>

Any questions, I put the rest of the code here for further understanding.

0

In the example I’ll leave, see the tag that has [attr.disabled], it will have the default value for a select, only that the value comes from Component.ts.

<div class="form-row">
    <div class="form-group col-md-5">
      <label for="componente">Componente</label>
      <select name="componente" id="componente" class="form-control componente" formControlName="id_componente" [attr.disabled]="true">
        <option value="{{ c.id_componente }}" *ngFor="let c of componentes" >{{c.nome_componente }}</option>
      </select>
    </div>
  </div>

I search in DB and insert in formBuilder, then it is preset selected within select.

ngOnInit() {
    this.setCurrentAction();

    this.funcionalidadesForm = this.formBuilder.group({
      id_funcionalidade: [null],
      nome_funcionalidade: [null, Validators.required],
      descricao: [null, Validators.required],
      id_componente: [null, Validators.required]
    });

    this.getListFormularios();
    this.loadPage();
  }
private loadPage() {
    if(this.currentAction == 'edit') {
      this.route.paramMap.pipe(
        switchMap(params => this.funcionalidadesService.getId(+params.get("id")))
      ).subscribe(
        (funcionalidade) => {
          this.updateForm(funcionalidade);
        }
      );
    }
  }

  private updateForm(item) {
    this.funcionalidadesForm.patchValue({
      id_funcionalidade: item[0].id_funcionalidade,
      nome_funcionalidade: item[0].nome_funcionalidade,
      descricao: item[0].descricao,
      id_componente: item[0].id_componente
    });
  }

0

Just take the [(ngModel)]="cliente.carros" of select and it automatically puts the preselected. I tested in the stackblitz and it worked.

0

Just try putting

[selected]="c.selected"
  • Unfortunately it didn’t work, and there was no mistake.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.