Reputation: 1643
I have an Angular component in which I created a two mat select fields.
My HTML code:
<mat-form-field>
<mat-select placeholder="Type" [(ngModel)]="Nm">
<mat-option [value]="'list'">
List
</mat-option>
<mat-option [value]="'text'">
Text
</mat-option>
<mat-option [value]="'radio'">
Radio
</mat-option>
<mat-option [value]="'label'">
Label
</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field>
<mat-select placeholder="Read" [(ngModel)] = "readFl">
<mat-option [value]="'Y'">Yes</mat-option>
<mat-option [value]="'N'">No</mat-option>
</mat-select>
</mat-form-field>
I have given default values to the two select options
public Nm: string = 'list';
public readFl: string = 'N';
I have a condition where if the selected value from the first dropdown is label
, then the second dropdown should be disabled and the value should be changed to Yes
.
How can I achieve such change with changing the value in the first dropdown?
Upvotes: 0
Views: 1663
Reputation: 1784
Usual way
To do this you can add a change event emitter to know when you change your value
<mat-select (selectionChange)="changeMethod()" placeholder="Type" [(ngModel)]="Nm">
Then in your ts file
changeMethod(){
if(this.Nm == 'label'){
this.readFl = 'Y'
}
}
And to disable your other selection you can either use an other variable as boolean and change it also in your changeMethod
or add this to your select <mat-select placeholder="Read" [(ngModel)] = "readFl" [disabled]="Nm == label">
. With Nm == label
the select will automatically set disabled to true if Nm == label.
Ternary operator
You can use the ternary operator that act like an If/Else statement, to check if you are on the label select directly on your template.
<mat-select placeholder="Read" [disabled]="Nm == 'label'"
[(ngModel)]="Nm == 'label' ? 'Y' : readFl">
By doing this you will do the following
if(Nm == 'label'){
return 'Y'
else
return readFl
This allow you to not add anything to your ts file, but doing this way, you will not store the 'Y' in your readFl
variable, so if you need the value then with a submit or something like that, you will have to do something like before, and checking if your Nm is 'label'.
So finally the first method is better if you need the value 'Y' or 'N' after.
Upvotes: 2