skip to Main Content

I have a dropdown menu with a couple of options and I want the first one to be selected by default, but it doesn’t work. I suspect this is because in the .ts file I initialize the control with the undifined value by default, but even if I try to pass a value inside it still nothing happens, how can I fix that?

HTML

<select  formControlName = "unit_measurement"  name="unit_measurment" id="unit_measurment">
            <option  selected disabled value="">Выберите ед. измерения</option>
            <option *ngFor="let um of unitMeasurements" [ngValue] = "um" value="">{{ um.value }}</option>
        </select>

TS

addForm = new FormGroup({
    name: new FormControl(undefined,[
      Validators.required
    ]),
    quantity: new FormControl(undefined,[
      Validators.required,
      Validators.min(0)
    ]),
    unit_cost: new FormControl(undefined,[
      Validators.required,
      Validators.min(0)
    ]),
    unit_measurement: new FormControl(undefined,[
      Validators.required
    ])
  })

enter image description here

I expect the first option tag to get selected by default

2

Answers


    1. update the Angular form like this

    Create unit_measurements enum and add the value into the form controller

    example for enum

    export enum unitMeasurement{
         //  unit measurements...
    };
    

    you have to remove by default and add the default value you want

    addForm = new FormGroup({
            name: new FormControl(undefined,[
              Validators.required
            ]),
            quantity: new FormControl(undefined,[
              Validators.required,
              Validators.min(0)
            ]),
            unit_cost: new FormControl(undefined,[
              Validators.required,
              Validators.min(0)
            ]),
            unit_measurement: new FormControl(undefined,[
              Validators.required
            ])
          })
    
    1. other one you can setValue for fromController in ngOnInit() example

      this.workOrderForm.get('unit_measurement').setValue('Выберите ед. измерения');

    Login or Signup to reply.
  1. ngOnInit() {
        // get the unit measurements (i guess they come from a service?)
        SOME_SERVICE.subscribe({
            next: (unitMeasurements) => {
    
                if (unitMEasurements.length > 0) {
                    // Update the form values all at once (just unit_measurement in this case)
                    this.addForm.patchValue({
                        // just selecting the first in array
                        unit_measurement: unitMeasurements[0]
                    })
                }
            }
        })
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search