Skip to content

Commit

Permalink
fix(material): revert required behavior for checkbox (#2358)
Browse files Browse the repository at this point in the history
fix #2349
  • Loading branch information
aitboudad committed Jul 12, 2020
1 parent 5d19b9f commit 3c08c38
Showing 1 changed file with 19 additions and 3 deletions.
22 changes: 19 additions & 3 deletions src/material/checkbox/src/checkbox.type.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Component, ViewChild } from '@angular/core';
import { Component, ViewChild, Renderer2, AfterViewChecked } from '@angular/core';
import { FieldType } from '@ngx-formly/material/form-field';
import { MatCheckbox, MatCheckboxChange } from '@angular/material/checkbox';

Expand All @@ -8,7 +8,6 @@ import { MatCheckbox, MatCheckboxChange } from '@angular/material/checkbox';
<mat-checkbox
[formControl]="formControl"
[id]="id"
[required]="to.required"
[formlyAttributes]="field"
[tabindex]="to.tabindex"
(change)="change($event)"
Expand All @@ -20,7 +19,7 @@ import { MatCheckbox, MatCheckboxChange } from '@angular/material/checkbox';
</mat-checkbox>
`,
})
export class FormlyFieldCheckbox extends FieldType {
export class FormlyFieldCheckbox extends FieldType implements AfterViewChecked {
@ViewChild(MatCheckbox) checkbox!: MatCheckbox;
defaultOptions = {
templateOptions: {
Expand All @@ -33,6 +32,11 @@ export class FormlyFieldCheckbox extends FieldType {
},
};

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

onContainerClick(event: MouseEvent): void {
this.checkbox.focus();
super.onContainerClick(event);
Expand All @@ -43,4 +47,16 @@ export class FormlyFieldCheckbox extends FieldType {
this.to.change(this.field, $event);
}
}

ngAfterViewChecked() {
if (this.required !== this._required && this.checkbox && this.checkbox._inputElement) {
this._required = this.required;
const inputElement = this.checkbox._inputElement.nativeElement;
if (this.required) {
this.renderer.setAttribute(inputElement, 'required', 'required');
} else {
this.renderer.removeAttribute(inputElement, 'required');
}
}
}
}

0 comments on commit 3c08c38

Please sign in to comment.