Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular - conditional element based on mat-select option

How am I able to achieve the following:

<mat-select formControlName="ctrlName">
    <mat-option *ngFor="let opt of options" [value]="opt.key">
        {{opt.label}}
    </mat-option>
</mat-select>

<div *ngIf=" SHOW IF A CERTAIN OPTION FROM THE LOOPED LIST ABOVE IS SELECTED "></div>

Sample list from the component:

options = [
    { key: 'keyOne', label: 'Key One 1' },
    { key: 'keyTwo', label: 'Key One 2' },
    { key: 'keyThree', label: 'Key One 3' }
]
like image 881
Tanasos Avatar asked Feb 04 '26 15:02

Tanasos


2 Answers

According to the angular material website (example here), you need to add [formControl]="selected" to the mat-select component.

   <mat-select [formControl]="selected">
        <mat-option *ngFor="let opt of options" [value]="opt">
            {{option.label}}
        </mat-option>
    </mat-select>

    <div *ngIf="selected===<your_specific_value>"></div>
like image 169
Ankit Sharma Avatar answered Feb 06 '26 07:02

Ankit Sharma


Because of the usage of formControls , I had to reference the entire form and specify the value:

*ngIf="form.value.specValue == 'valueName'"
like image 34
Tanasos Avatar answered Feb 06 '26 06:02

Tanasos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!