角度材料单选按钮已选中

时间:2017-10-09 14:01:04

标签: angular angular-material2

我有这个组件代码(我只保留抛出此错误所需的代码):

    import {
      Component,
      OnInit,
      ChangeDetectorRef
    } from '@angular/core';

@Component({
  /**/
})
export class ManageUsersComponent implements OnInit {

  public dataSource: UserDataSource | null;
  public users: IUser[] = [];
  public metadata: Metadata[] = [];
  public displayedColumns = [
    'lastname',
    'firstname',
    'email',
    'administrator',
    'advancedUser',
    'collaborator',
    'actions'
  ];

    constructor(private cdr: ChangeDetectorRef) {}

    onChange(): void {
      this.cdr.detectChanges();
    }

    ngOnInit(): void {
        this.dataSource = null;

    // Get users from server
    this.userService.getUsers().subscribe(response => {

        let _users = response.users;
        this.metadata = response.metadata;

        for (let i = 0; i < _users.length; i++) {
            this.users.push(_users[i]);
        }

        // Set data table source
        this.dataSource = new UserDataSource(this.users);

    }, errorResponse => {
        console.log(errorResponse);
    });
    }
}

我有这个模板代码:

<ng-container matColumnDef="administrator">
         <mat-header-cell *matHeaderCellDef> Administrateur </mat-header-cell>
         <mat-cell *matCellDef="let user">
             <mat-radio-button color="primary" 
                           name="radio_{{user.id}}"
                           checked="true"
                           value="ROLE_ADMIN"
                           (change)="setRoles($event, user)">
         </mat-radio-button>
         {{user.authorities[0]?.name == 'ROLE_ADMIN'}} <!-- This is true -->
     </mat-cell>
</ng-container>

但是我收到了这个错误:

ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'false'. Current value: 'false'

我已经阅读了这个错误,但无法理解它如何在此上下文中修复它。这是一个视图,我只是从材料设计中更改checked属性。

问题在于checked属性。

任何人都可以帮助我吗?

比你提前。

祝你好运, 马塞洛

1 个答案:

答案 0 :(得分:0)

尝试将ChangeDetectionRef注入您的组件

constructor(private cdr: ChangeDetectionRef) {
}

onChange(): void {
  this.val += 1; // <- get error after
  this.cdr.detectionChanges();
}

或者从您的enableProdMode()文件

中拨打main.ts