【问题标题】:how to select options when a edit mode using Material Design使用 Material Design 编辑模式时如何选择选项
【发布时间】:2020-08-14 09:15:33
【问题描述】:

我正在使用下拉菜单来选择多个角色。单击编辑按钮时,我想将2 roles 签出3 roles。因为用户在admin, dashboards, user 中有两个角色admin, dashboards

我将检查来自服务器的角色和角色列表,如果角色名称相同,我将创建selected = true。所以,我只能选择selected is true 的选项。 我如何意识到这一点?此代码基于Angular 8

打字稿

this.user.roles = roles;

榜样

    id: number;
    name: string; 
    selected :boolean;

html

<div class="col-lg-6 kt-margin-bottom-20-mobile">
    <mat-form-field class="mat-form-field-fluid">
        <mat-select placeholder="Role"
                    formControlName="roles"
                    multiple>
            <mat-option *ngFor="
                    let role of roles$ | async " [value]="role">
                {{ role.name }}
            </mat-option>
        </mat-select>
        <mat-error *ngIf="isControlHasError('roles','required')">
            <strong>{{ 'AUTH.VALIDATION.REQUIRED_FIELD' | translate }}</strong>
        </mat-error>
    </mat-form-field>
</div>

【问题讨论】:

  • 使用 [(ngModel)]="role" 代替 mat 选项中的值

标签: angular angular8


【解决方案1】:

要对预选/默认值进行双向绑定,请使用[formControl]

<mat-select placeholder="Role" [formControl]="selectedRole" multiple>
  <mat-option *ngFor="let role of roles$ | async " [value]="role.id">
    {{ role.name }}
  </mat-option>
</mat-select>

在 .component.ts 中,你的代码应该是这样的

selectedRole= new FormControl();
ngOnInit(){
  getUserRole()
}

getUserRole(){
...
this.selectedRole.setValue(role.id)  // role = {id:3,name:'user'}
}

【讨论】:

  • 这会给我两个选择。我想要做的是从三个选项中选择两个。
  • selectedRole 应该具有&lt;mat-option&gt;[value] 字段
  • 请检查更新后的答案,您还需要使[value] 字段不是对象
  • 其他表单控件究竟是用什么做的?还使用我分享的示例,您没有使用任何 formControlName 属性
  • stackoverflow.com/questions/40171914/… 我想继续使用 formControlName 而不是 formControl。我可以选择两个角色吗?而不是一个?
猜你喜欢
  • 1970-01-01
  • 2017-08-01
  • 2020-04-10
  • 2018-12-19
  • 1970-01-01
  • 2017-02-23
  • 2018-07-15
  • 1970-01-01
  • 2019-02-18
相关资源
最近更新 更多