Euridice01
Euridice01

Reputation: 2568

Dynamically changing the selected value of dropdown

So I have an odd behavior that I want to implement on my dropdown. I have two scenarios and both will have different default selected values.

Scenario 1: If user role is admin, then dropdown will not be disabled and 'Select Location' placeholder will show up as selected default.

Scenario 2: if user role is clerk, then dropdown will be disabled and the selected value will be a specific location from the dropdown selection.

While I got the role permission and disabled/enabled thing setup, I'm not sure how to dynamically change the selected value of the dropdown. This is inside reactive forms form group, so not sure I can use ngModel or can I?

Here's my dropdown:

 <select [ngModel]="null" formControlName="location" required >
    <option value="null" disabled>{{'SelectLocation' | translate}}</option>
    <option selected *ngFor="let store of location" [ngValue]="store._storeKey">{{ store._storeName }}</option>
</select>

Here's the check I have that disables/enables the dropdown:

checkUserPermissions() {
    if (this.userPermissions._userPrivilegeKey === 100) {
      //TODO: Default to store2 of list for example
      this.transactionForm.controls['location'].value = stores._store; // This is right? 
      this.transactionForm.controls['location'].disable();
    } else if (this.userPermissions._userPrivilegeKey === 200) {
      //TODO: Default to select location placeholder (currently working)
      this.transactionForm.controls['location'].enable();
    } 
  }

Upvotes: 1

Views: 877

Answers (1)

Manzur Khan
Manzur Khan

Reputation: 2486

You should use the patchValue function instead of directly assigning the value when dealing with forms

this.transactionForm.controls['location'].patchValue(stores._store)

Upvotes: 1

Related Questions