Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(core): support "required" indicator for custom form-controls #2068

Merged
merged 6 commits into from
Nov 15, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
FormGroupDirective,
NgControl,
NgForm,
Validators,
} from "@angular/forms";
import { MatFormFieldControl } from "@angular/material/form-field";
import {
Expand All @@ -28,7 +29,16 @@ export abstract class CustomFormControlDirective<T>
// eslint-disable-next-line @angular-eslint/no-input-rename
@Input("aria-describedby") userAriaDescribedBy: string;
@Input() placeholder: string;
@Input() required = false;

@Input()
get required() {
return this._required;
}
set required(req: boolean) {
this._required = coerceBooleanProperty(req);
this.stateChanges.next();
}
private _required = false;

abstract inputElement: { _elementRef: ElementRef<HTMLElement> };
stateChanges = new Subject<void>();
Expand Down Expand Up @@ -123,21 +133,40 @@ export abstract class CustomFormControlDirective<T>
this.disabled = isDisabled;
}

ngDoCheck() {
const control = this.ngControl
? (this.ngControl.control as AbstractControl)
: null;

this.checkUpdateErrorState(control);
this.checkUpdateRequired(control);
}

/**
* Updates the error state based on the form control
* Taken from {@link https://github.com/angular/components/blob/a1d5614f18066c0c2dc2580c7b5099e8f68a8e74/src/material/core/common-behaviors/error-state.ts#L59}
*/
ngDoCheck() {
private checkUpdateErrorState(control: AbstractControl | null) {
const oldState = this.errorState;
const parent = this.parentFormGroup || this.parentForm;
const control = this.ngControl
? (this.ngControl.control as AbstractControl)
: null;
const newState = this.errorStateMatcher.isErrorState(control, parent);

if (newState !== oldState) {
this.errorState = newState;
this.stateChanges.next();
}
}

private checkUpdateRequired(control: AbstractControl | null) {
if (!control) {
return;
}

if (
this.required !==
coerceBooleanProperty(control.hasValidator(Validators.required))
) {
this.required = control.hasValidator(Validators.required);
}
}
}