submenús sencillo realizar menú menus hacer facil desplegables desplegable con como javascript html angular typescript

javascript - sencillo - Opción de selección Angular 2(menú desplegable): ¿cómo obtener el valor al cambiar para que se pueda utilizar en una función?



menus desplegables en php (6)

Estoy tratando de construir un menú desplegable con algunos valores.

Sin embargo, al seleccionar un valor, quiero hacer una llamada a la API que tome una identificación.

En mi component.ts, tengo una matriz de valores:

values = [ { id: 3432, name: "Recent" }, { id: 3442, name: "Most Popular" }, { id: 3352, name: "Rating" } ];

En mi plantilla, estoy usando esa matriz de la siguiente manera:

<select> <option *ngFor="let v of values" [value]="v"> {{v.name}} </option> </select>

Sin embargo, al seleccionar un valor del menú desplegable, ¿cómo puedo acceder a la propiedad de id ? Quiero usar eso en mi función getPhotosByType(id) .

Gracias


Debe utilizar una directiva de formulario angular en la select . Puedes hacerlo con ngModel . Por ejemplo

@Component({ selector: ''my-app'', template: ` <h2>Select demo</h2> <select [(ngModel)]="selectedCity" (ngModelChange)="onChange($event)" > <option *ngFor="let c of cities" [ngValue]="c"> {{c.name}} </option> </select> ` }) class App { cities = [{''name'': ''SF''}, {''name'': ''NYC''}, {''name'': ''Buffalo''}]; selectedCity = this.cities[1]; onChange(city) { alert(city.name); } }

El (ngModelChange) eventos (ngModelChange) emite eventos cuando cambia el valor seleccionado. Aquí es donde puede conectar su devolución de llamada.

Tenga en cuenta que deberá asegurarse de haber importado FormsModule en la aplicación.

Aquí hay un Plunker


Mi respuesta es un poco tarde pero simple; pero puede ayudar a alguien en el futuro; Experimenté con angular tanto 4.4.3, 5.1+, 6.xy 7.x usando $ event (más reciente en este momento)

Modelo:

<select (change)="onChange($event)"> <option *ngFor="let v of values" [value]="v.id">{{v.name}}</option> <select>

TS

export class MyComponent { public onChange(event): void { // event will give you full breif of action const newVal = event.target.value; console.log(newVal); } }


Otra solución sería, puede obtener el objeto en sí mismo como valor si no menciona su id como valor : Nota: [valor] y [ngValue] ambos funcionan aquí.

<select (change)="your_method(values[$event.target.selectedIndex])"> <option *ngFor="let v of values" [value]="v" > {{v.name}} </option> </select>

En ts:

your_method(v:any){ //access values here as needed. // v.id or v.name }

Nota: Si está utilizando un formulario reactivo y desea capturar un valor seleccionado en el formulario Enviar, debe usar la directiva [ngValue] en lugar de [valor] en el scanerio anterior

Ejemplo:

<select (change)="your_method(values[$event.target.selectedIndex])" formControlName="form_control_name"> <option *ngFor="let v of values" [ngValue]="v" > {{v.name}} </option> </select>

En ts:

form_submit_method(){ let v : any = this.form_group_name.value.form_control_name; }


Plantilla / Archivo HTML (component.ts)

<select> <option *ngFor="let v of values" [value]="v" (ngModelChange)="onChange($event)"> {{v.name}} </option> </select>

Archivo Typescript (component.ts)

values = [ { id: 3432, name: "Recent" }, { id: 3442, name: "Most Popular" }, { id: 3352, name: "Rating" } ]; onChange(cityEvent){ console.log(cityEvent); // It will display the select city data }

(ngModelChange) es @Output de la directiva ngModel. Se dispara cuando el modelo cambia. No puedes usar este evento sin la directiva ngModel


values_of_objArray = [ { id: 3432, name: "Recent" }, { id: 3442, name: "Most Popular" }, { id: 3352, name: "Rating" } ]; private ValueId : number = 0 // this will be used for multi access like // update, deleting the obj with id. private selectedObj : any; private selectedValueObj(id: any) { this.ValueId = (id.srcElement || id.target).value; for (let i = 0; i < this.values_of_objArray.length; i++) { if (this.values_of_objArray[i].id == this.ValueId) { this.selectedObj = this.values_of_objArray[i]; } } }

Ahora juegue con this.selectedObj que tiene el objeto seleccionado de la vista.

HTML:

<select name="values_of_obj" class="form-control" [(ngModel)]="ValueId" (change)="selectedValueObj($event)" required> <option *ngFor="let Value of values_of_objArray" [value]="Value.id">{{Value.name}}</option> </select>


<select [(ngModel)]="selectedcarrera" (change)="mostrardatos()" class="form-control" name="carreras"> <option *ngFor="let x of carreras" [ngValue]="x"> {{x.nombre}} </option> </select>

En ts

mostrardatos(){ }