typescript - Angular 2: Cuando se dispara onChange, ¿cómo recuperar tanto el valor seleccionado como el id del elemento select?
Aquí está el código en la plantilla:
<select id="regionSelection" [(ngModel)]="regionId"
(change)="onChange($event.target.value)"
class = "form-control">
<option *ngFor="let r of regionsForDDL"
value="{{ r.key }}">{{ r.value }}</option>
</select>
y el código en el componente
onChange(selectedValue: string) {
}
$event.target.value solo envía el valor seleccionado. ¿Cómo puedo obtener tanto el valor seleccionado como el id del elemento (aquí regionSelection)?
Gracias por ayudar
Respuesta #1
Simplemente pásalo así:
(change)="onChange($event.target.id, $event.target.value)"
onChange(id: string, selectedValue: string) {
}
Respuesta #2
html
(change)="onChange($event.target)"
ts
onChange({ id, value }) {
console.log(id, value);
}
o
onChange({ id, value: selectedValue }) {
console.log(id, selectedValue);
}
https://stackblitz.com/edit/angular-7ysmjr?file=app%2Fapp.component.ts
Ve más detalles sobre cómo funciona la sintaxis de asignación por desestructuración
- https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Unpacking_fields_from_objects_passed_as_function_parameter
