How to set default option in select when we use Object populate select option from Reactive...

Discussão em 'Angular' iniciado por Parth Patel, Dezembro 2, 2024.

  1. Parth Patel

    Parth Patel Guest

    I've one pop up form in which there is select option, you can think of various option of food dishes, now I have following code to select the option and submit. But currently, after update when I reopen the pop up form, the select field is blank. In db it is storing perfect option.

    component.ts:

    dishes: any[] = [];
    updateFoodDishesForm: UntypedFormGroup;
    selectForUpdate: any;

    constructor(){
    this.updateFoodDishesForm = new UntypedFormGroup({
    // Food dishes is an object in backend which has multiple field such as id, name
    foodDishes: new UntypedFormControl('')
    });
    }

    ngOnInit() {
    // Loading food dishes option for select element
    this.dishesService.getAllFoodDishesDetails().subscribe((dishes ) => {
    this.dishes = dishes;
    });
    // we are setting selectForUpdate before calling the modal pop up
    this.selectForUpdate = dishesService.getCurrentFoodDetails();
    }

    openModalForm() {
    let foodUpdateFormData = {
    foodDishes: this.selectForUpdate.foodDishes
    };
    this.updateFoodDishesForm.patchValue(foodUpdateFormData);
    }


    template:

    <div class="mb-3">
    <label class="control-label requiredField">
    {{ 'Select Food dishes:' | translate }}
    <span class="asteriskField"> *</span>
    </label>
    <select id="foodDishes" formControlName="foodDishes" class="form-control">
    <option value="" disabled [selected] >Select Option</option>
    <option *ngFor="let indianDish of dishes" [ngValue]="dish">{{ indianDish.name }} ({{indianDish.id }})</option>
    </select>
    </div>

    Continue reading...

Compartilhe esta Página