schuno
schuno

Reputation: 585

Angular 6 - Dynamically set [required] on mat-select

In my Angular v6 app, I am trying to display a drop-down and set it as required based on a boolean value, where it is set on a checkbox's value. Here is a snippet of that code in my template (includeModelVersion is initially set to false):

<mat-checkbox class='matCheckbox' (change)="includeModelVersion = !includeModelVersion">Run Model</mat-checkbox>&nbsp;&nbsp;&nbsp;&nbsp;
<mat-form-field *ngIf="includeModelVersion">
  <mat-select placeholder="Select Model Version" formControlName="modelVersionCtrl" [required]="includeModelVersion">
    <mat-option *ngFor="let model of modelData" [value]="model?.MODEL_VERSION">{{model.MODEL_VERSION}}</mat-option>
  </mat-select>
</mat-form-field>

In my .ts constructor I am defining my boolean value:

includeModelVersion: boolean = false;

The drop down is displaying properly, using the *ngIf, but the issue is related to [required]="includeModelVersion" within mat-select.

If I do not check the checkbox then the form is able to submit fine, but if I check the checkbox and then uncheck it, the drop-down remains required, even though includeModelVersion=false.

Am I missing something here, or am I defining something incorrectly?

Upvotes: 2

Views: 7658

Answers (2)

Danish Arora
Danish Arora

Reputation: 338

Updated Answer

You are using reactive forms, I think you can define Validators.required when defining the form control inside a form group like this:

this.fb.group({
  'modelVersionCtrl': ['', Validators.required]
})

If you want to compose your required based on some condition, try Validators.compose([<your conditional logic here>]).

The beauty of Angular Reactive Forms is having validations set programmatically rather than in the template. Hope that helped!

Upvotes: 0

ronakvp
ronakvp

Reputation: 177

If you are using reactive forms, you can dynamically add 'required' validator to the the formControl.

this.form.controls["modelVersionCtrl"].setValidators(Validators.required);

You can execute this statement based on certain conditions in the component class.

Upvotes: 5

Related Questions