Angular 6 How to leave default field in select?

Asked

Viewed 645 times

0

I’m trying to leave one of the option elements as Selected, but I can’t get it to work at Angular 6.

app.component.html:

<select [(ngModel)]="marcaSelecionada" class="form-control" name="marca" required>
  <option value="">Selecione uma marca...</option>
  <option *ngFor="let marca of marcas" [ngValue]="marca.id">{{ marca.nome_marca | uppercase }}</option>
</select>

app.componentts.:

import { Component, OnInit } from '@angular/core';
import { AtualizaFormularioService } from './atualiza-formulario.service';

interface MarcaModelo {
  id?: string;
  nome_marca?: string;
}

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {

  public marcas: MarcaModelo[];
  public campoMarca: MarcaModelo = {
    nome_marca: ''
  }
  public marcaSelecionada: string = '2';

}
  • In this case the id of the object you are comparing has to be equal to what you left by default.

1 answer

0

Try placing the value attribute of the select tag with the value you want it to load selected:

<select [(ngModel)]="marcaSelecionada" class="form-control" name="marca" value="marcaSelecionada" required>
  <option value="">Selecione uma marca...</option>
  <option *ngFor="let marca of marcas" [ngValue]="marca.id">{{ marca.nome_marca | uppercase }}</option>
</select>

- Related question.

- Follow an example

Browser other questions tagged

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