Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Comercial
    • Calculadora

0

100
Vistas
Angular select defaults to the 2nd option, why?

I have an array of objects from which I render a select. The problem is that the select defaults its selection to the 2nd object(which shouldn't even be selectable, just used as a category label) in the warehouseSelect array(hence why I also tried to use the unshift method as well).

What would possess Angular to resort to such behavior?

Angular HTML

<select [disableControl]="allDisabled" class="form-control" id="warehouse_id" formControlName="warehouse_id" tooltip="Select a warehouse" data-placement="top">
    <option *ngFor="let warehouse of warehouseSelect" [disabled]="warehouse.id == null" [selected]="orderform.controls['warehouse_id'].value == warehouse.id" [ngValue]='warehouse.id' id="{{warehouse.id}}">{{warehouse.name}}</option>
</select>

Typescript

constructor(
    private warehouseService: WarehouseService,
) {
    this.warehouseService.getWarehouses(this.selectedOrganization.organization_id)
        .subscribe((warehouses) => {

            warehouses.forEach(warehouse => {
                if (!this.purposesWarehouses[warehouse.purpose]) {
                    this.purposesWarehouses[warehouse.purpose] = [];
                }
                this.purposesWarehouses[warehouse.purpose].push(warehouse);
                this.warehouses.push(warehouse);
            });
            for (let purpose in this.purposesWarehouses) {
                this.warehouseSelect.push({ id: null, name: purpose });
                for (let warehouse in this.purposesWarehouses[purpose]) {
                    this.warehouseSelect.push(this.purposesWarehouses[purpose][warehouse]);
                }
            }
            this.warehouseSelect.unshift({ id: -1, name: 'Auto', });
        });
}
7 months ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Since your orderform.controls['warehouse_id']'s initial value is null, the one with null id is selected by default.

You can change the value of the form control using setValue function.

For example: orderform.controls['warehouse_id'].setValue(1) the item with id of 1 will be selected by default

7 months ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos