[Fixed] Angular CLI disable html form if previous option not selected?

Issue

I have a form that has a few select fields populated with options.

    <form [formGroup]="selectVehicleForm">
        
    <select formControlName="Manufacturer">
    <option *ngFor='let cars of cars$'>{{cars.Manufacturer}}</option>
    </select>

     <select formControlName="Model">
     <option *ngFor='let cars of cars$'>{{cars.Model}}</option>
     </select>
</form>

My question – how can I disable my "Model" field as long as a user has nothing selected in "Manufacturer"?

Solution

You can try like this (not tested) :

constructor(private fb: FormBuilder) {
  this.selectVehicleForm = this.fb.group({
    Manufacturer: [],
    Model: [{ value: '', disabled: true }]
  )};

  this.selectVehicleForm.get('Manufacturer').valueChanges.subscribe(value => {
    if (value) {
      this.selectVehicleForm.get('Model').enable();
    } else {
      this.selectVehicleForm.get('Model').reset('');
      this.selectVehicleForm.get('Model').disable();
    }
    this.selectVehicleForm.updateValueAndValidity();
  })
}

Leave a Reply

(*) Required, Your email will not be published