如何在 Angular Material 表中显示选择列表?

问题描述

如何在 Angular Material 表中显示选择列表?

错误

TS2339: Property 'element' does not exist on type 'MyaccountComponent'.

<mat-option *ngFor="let role of element.validRoles" [value]="role.value">

如果我也将 element.validRoles 更改为 validRoles,我也会收到同样的错误

组件:

export class MyaccountComponent implements OnInit {

  displayedColumns: string[] = ['email','role','rolestatus','validRoles'];
  dataSource = [];

  ngOnInit(){
    this.getAllUsers();
  }

  constructor(private userService: UserService) { }

  getAllUsers(){
    const obs = this.userService.getAllRegisteredUsers();
    obs.subscribe(data => {
      console.log(data.users);
      this.dataSource = data.users
    });
  }

}

模板:

<ng-container matColumnDef="validRoles">
    <th mat-header-cell *matHeaderCellDef> Assign Role</th>
    <mat-form-field appearance="fill">
        <mat-label>Roles</mat-label>
        <mat-select>
          <mat-option *ngFor="let role of element.validRoles" [value]="role.value">
            {{role.viewvalue}}
          </mat-option>
        </mat-select>
      </mat-form-field>
</ng-container>

我的数据格式为:

data.users.validRoles = [
         {value: "admin",viewvalue: "Admin"}
];

解决方法

组件上没有名为 element 的属性

用 dataSource.validRoles 替换 element.validRoles

,

需要进行一些更改。将选择列表选项数据移至组件,而不是来自后端。

模板也缺少以下几行:

<td mat-cell *matCellDef>

</td>

更新的模板:

<ng-container matColumnDef="validRoles">
  <th mat-header-cell *matHeaderCellDef> Assign Role</th>
  <td mat-cell *matCellDef>
  <mat-form-field appearance="fill">
      <mat-label>Roles</mat-label>
      <mat-select>
        <mat-option *ngFor="let role of validRoles" [value]="role.value">
          {{role.viewvalue}}
        </mat-option>
      </mat-select>
    </mat-form-field>
  </td>
</ng-container>