简体   繁体   中英

Binding select/options Angular 8

StackBlitz:

https://stackblitz.com/edit/angular-mezz1b

I have this model:

import { Users } from './Users';
import { Puntos } from './Puntos';
import { Empleados } from './Empleados';

export class PuntosEmpleados {
    Id?: number;
    Fecha?: string;
    Puntos?: Puntos;
    User?: Users;
    Empleado?: Empleados;
}

My PuntosEmpleados.TS:

 PuntoEmpleado: PuntosEmpleados = {};

 Puntos: Puntos[] = [];
 Empleados: Empleados[] = [];
 Usuarios: Users[] = [];

My PuntosEmpleados.HTML: (the same with Puntos and Usuarios)

<div class="form-group col-md-6">
    <label>Empleado: </label>
    <select class="form-control form-control-sm" name="empleado"
        [(ngModel)]="PuntoEmpleado.Empleado" >
        <option *ngFor="let emp of Empleados" [ngValue]="emp">
            {{ emp.Nombre }} {{ emp.Apellido }}
        </option>
    </select>
</div>

My problem is when i want to edit one employee(Empleado). Passed the employee to PuntoEmpleado Object, but in the selects doesn´t show the descriptions(Nombre, Apellido, etc..)

I try to define de model in the component.ts and it works fine, but i don´t want that.

I looked for some similar queries but none with the same error.

Thanks in advance.

Is the Empleado property from the PuntoEmpleado object an instance of an object in the Empleados array? ngValue and ngModel are only going to match an object if they are the same instance, not objects with the same values or value type objects like strings or numbers.

Just like how these two identical objects are not equal, ngModel wont match two objects that are not the same instance.

 console.log({ prop: '1' } === { prop1: '1' });

You can either use a value property in the PuntoEmpleado object like id, they will match or you can look up the instance of the object from the array and assign it to the Empleado property.

Here is an edit of your StackBlitz where I have put the Empleado from the PuntoEmpleado in the Empleados array. It works because it is the same reference of the object. https://stackblitz.com/edit/angular-rhrzhf

My strategy would be to have an EmpleadoId property on the PuntosEmpleados object and bind to that.

<div class="form-group col-md-6">
    <label>Empleado: </label>
    <select class="form-control form-control-sm" name="empleadoId"
        [(ngModel)]="PuntoEmpleado.EmpleadoId" >
        <option *ngFor="let emp of Empleados" [ngValue]="emp.Id">
            {{ emp.Nombre }} {{ emp.Apellido }}
        </option>
    </select>
</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM