Skip to content

Commit

Permalink
fix(material): trigger focus/blur event for mat-checkbox (#2611)
Browse files Browse the repository at this point in the history
fix #2602
  • Loading branch information
aitboudad committed Dec 5, 2020
1 parent 22ff9ca commit 81f523f
Showing 1 changed file with 18 additions and 3 deletions.
21 changes: 18 additions & 3 deletions src/material/checkbox/src/checkbox.type.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Component, ViewChild, Renderer2, AfterViewChecked } from '@angular/core';
import { Component, ViewChild, Renderer2, AfterViewChecked, OnDestroy, AfterViewInit } from '@angular/core';
import { FieldType } from '@ngx-formly/material/form-field';
import { MatCheckbox } from '@angular/material/checkbox';
import { FocusMonitor } from '@angular/cdk/a11y';

@Component({
selector: 'formly-field-mat-checkbox',
Expand All @@ -18,7 +19,7 @@ import { MatCheckbox } from '@angular/material/checkbox';
</mat-checkbox>
`,
})
export class FormlyFieldCheckbox extends FieldType implements AfterViewChecked {
export class FormlyFieldCheckbox extends FieldType implements AfterViewInit, AfterViewChecked, OnDestroy {
@ViewChild(MatCheckbox) checkbox!: MatCheckbox;
defaultOptions = {
templateOptions: {
Expand All @@ -32,7 +33,7 @@ export class FormlyFieldCheckbox extends FieldType implements AfterViewChecked {
};

private _required!: boolean;
constructor(private renderer: Renderer2) {
constructor(private renderer: Renderer2, private focusMonitor: FocusMonitor) {
super();
}

Expand All @@ -41,6 +42,16 @@ export class FormlyFieldCheckbox extends FieldType implements AfterViewChecked {
super.onContainerClick(event);
}

ngAfterViewInit() {
this.focusMonitor.monitor(this.checkbox._inputElement, true).subscribe(focusOrigin => {
if (focusOrigin) {
this.to.focus && this.to.focus(this.field);
} else {
this.to.blur && this.to.blur(this.field);
}
});
}

ngAfterViewChecked() {
if (this.required !== this._required && this.checkbox && this.checkbox._inputElement) {
this._required = this.required;
Expand All @@ -52,4 +63,8 @@ export class FormlyFieldCheckbox extends FieldType implements AfterViewChecked {
}
}
}

ngOnDestroy() {
this.focusMonitor.stopMonitoring(this.checkbox._inputElement);
}
}

0 comments on commit 81f523f

Please sign in to comment.