Búsqueda de sitios web

Seleccionar valor de opción predeterminada desde TypeScript Angular 6


Tengo un HTML select así:

<select ng-model='nrSelect' class='form-control'>                                                                
    <option value='47'>47</option>
    <option value='46'>46</option>
    <option value='45'>45</option>
</select>

¿Cómo puedo seleccionar el valor predeterminado de TypeScript, por ejemplo 47?

Respuesta #1

Puedes hacer esto:

<select  class='form-control' 
        (change)="ChangingValue($event)" [value]='46'>
  <option value='47'>47</option>
  <option value='46'>46</option>
  <option value='45'>45</option>
</select>

// Note: You can set the value of select only from options tag. In the above example, you cannot set the value of select to anything other than 45, 46, 47.

Aquí, puedes jugar con esto.

Respuesta #2

app.component.html

<select [(ngModel)]='nrSelect' class='form-control'>
  <option value='47'>47</option>
  <option value='46'>46</option>
  <option value='45'>45</option>
</select>

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  nrSelect = 47
}

Respuesta #3

Para el formulario reactivo, logré que funcionara usando el siguiente ejemplo (47 se puede reemplazar con otro valor o variable):

<div [formGroup]="form">
  <select formControlName="fieldName">
    <option
        *ngFor="let option of options; index as i"
        [selected]="option === 47"
    >
        {{ option }}
    </option>
  </select>
</div>

Respuesta #4

La manera correcta sería:

<select id="select-type-basic" [(ngModel)]="status">
    <option *ngFor="let status_item of status_values">
    {{status_item}}
    </option>
</select>

Se debe evitar el valor dentro de la opción si el valor va a ser dinámico, ya que eso establecerá el valor predeterminado del 'campo de selección'. La selección predeterminada debe estar vinculada con [(ngModel)] y las opciones deben declararse de manera similar.

status : any = "47";
status_values: any = ["45", "46", "47"];

Artículos relacionados