简体   繁体   中英

How can I display a select list within an Angular Material table?

How can I display a select list within an Angular Material table?

error:

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

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

I get the same error if I change element.validRoles to validRoles too.

Component:

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
    });
  }

}

Template:

<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>

My data is in the format:

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

You have no property named element on the component

Replace element.validRoles with dataSource.validRoles

A couple of changes were required. Moved the select list option data to the component instead of it coming from the backend.

Also the template was missing these lines:

<td mat-cell *matCellDef>

</td>

The updated the template:

<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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM