How to obtain the selected value of a SELECT in Angular 4?

2

I'm starting in the Angular 4 framework, and I have a question about Select, I need to know what option the user of my Select selects.

In my App.component.html I have this code:

<select name="" id="cantidad" (change)="capturar()">
  <option *ngFor="let dato of datos">
    {{dato}}
  </option>
</select>

And in my app.component.ts I have this:

import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  datos;
  constructor(){
    this.datos=[1,2,3,4,5,6,7,8,9,10];
  }
  capturar(){

  }
}
    
asked by Cristian D. 30.09.2017 в 20:34
source

1 answer

2

You were very close, you have to use the directive (ngModel) to be able to get the value of <select> :

View Demo Online

<select [(ngModel)]="opcionSeleccionado" (change)="capturar()">
    <option value="0">Selecciona una opción</option>
    <option *ngFor="let dato of datos">
      {{dato}}
    </option>
</select>

<!-- Prueba para ver la opción seleccionado -->
<p [hidden]="opcionSeleccionado == '0'">Haz seleccionado la opción # {{ verSeleccion }}</p>
export class AppComponent  {
  datos;
  // Seleccionamos o iniciamos el valor '0' del <select>
  opcionSeleccionado: string  = '0';
  verSeleccion: string        = '';

  constructor(){
      this.datos = [1,2,3,4,5,6,7,8,9,10];
  }  

  capturar() {
      // Pasamos el valor seleccionado a la variable verSeleccion
      this.verSeleccion = this.opcionSeleccionado;
  }
}
    
answered by 01.10.2017 / 12:15
source