所以我想在下拉列表中实现一个奇怪的行为。我有两种情况,两种情况都有不同的默认选择值。
场景 1:如果用户 Angular 色是管理员,则不会禁用下拉菜单,并且“选择位置”占位符将显示为选定的默认值。
场景 2:如果用户 Angular 色是职员,则下拉列表将被禁用,并且所选值将是下拉选项中的特定位置。
虽然我获得了 Angular 色权限并禁用/启用了事物设置,但我不确定如何动态更改下拉列表的选定值。这是在响应式(Reactive)表单组内,所以不确定我可以使用 ngModel 还是可以?
这是我的下拉菜单:
<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>
这是我禁用/启用下拉列表的检查:
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();
}
}
最佳答案
处理表单时应该使用 patchValue 函数,而不是直接赋值
this.transactionForm.controls['location'].patchValue(stores._store)
关于javascript - 动态更改下拉列表的选定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49568110/