Skip to content

bug(mat-checkbox): detectChanges does not work in detached mode #25991

Open
@scharf

Description

@scharf

The previous version in which this bug was not present was

No response

Description

Running detectChanges() for components with changeDetection: ChangeDetectionStrategy.OnPush does not work as expected

Reproduction

Here is a simple stackblitz to test the Problem (https://stackblitz.com/edit/angular-4csuvx-hrjdpp?file=src/app/checkbox-reactive-forms-example.ts)

Here is the essence of the stackblitz example:

mport { Component } from '@angular/core';

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

/** @title Checkboxes with reactive forms */
@Component({
  changeDetection: ChangeDetectionStrategy.OnPush,
  selector: 'checkbox-reactive-forms-example',
  template: `
    <input type="checkbox" [(ngModel)]="checked" /> Normal Checkbox 
    <br>   
    <input type="checkbox" [(ngModel)]="checked" /> Normal Checkbox Linked to samd data
    <br>
    <code>[{{checked?"X":" "}}]</code> State of check variable<br>   
    <mat-checkbox [(ngModel)]="checked">MAT Checkbox not working</mat-checkbox>
    <br>
    <mat-checkbox [(ngModel)]="checked">MAT Checkbox not working</mat-checkbox>
  `,
})
export class CheckboxReactiveFormsExample implements OnInit {
  constructor(private ref: ChangeDetectorRef) {
    ref.detach();
  }
  ngOnInit() {
    // needed for the initial drawing
    this.ref.detectChanges();
  }
  private _checked = true;
  get checked() {
    return this._checked;
  }
  set checked(c) {
    this._checked = c;
    this.ref.detectChanges();
  }
}

Expected Behavior

The checkbox should reflect the state of the model after a call to detectChanges()

Actual Behavior

The checkbox is out of sync with the model.

Environment

  • Angular:
  • CDK/Material:
  • Browser(s):
  • Operating System (e.g. Windows, macOS, Ubuntu):

Metadata

Metadata

Assignees

No one assigned

    Labels

    P4A relatively minor issue that is not relevant to core functionsarea: material/checkbox

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions