0

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"?

2 Answers 2

1

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();
  })
}
Sign up to request clarification or add additional context in comments.

2 Comments

Works well, thank you so much, marking as answer asap
Great ! Could you please mark it as resolved ? :D
1

You can listen (change) on the FormControl Manufacturer and call enable()/disable() on the FormControl Model

See the Stackblitz

Relevant parts are :

HTML

  <select formControlName="Manufacturer" (change)="onChangeManufacturer($event)">
    <option *ngFor='let cars of cars$'>{{cars.Manufacturer}}</option>
  </select>

Typescript

  selectVehicleForm = new FormGroup({
    Manufacturer: new FormControl(),
    Model: new FormControl(),
  });

  ngOnInit() {
    this.selectVehicleForm.controls['Model'].disable();
  }

  onChangeManufacturer(value) {
    const formControlModel = this.selectVehicleForm.controls['Model'];
    if(this.selectVehicleForm.controls['Manufacturer']) {
      formControlModel.enable();
    } else {
      formControlModel.disable();
    } 
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.