Skip to content

Instantly share code, notes, and snippets.

@partyka1
Last active April 18, 2020 13:09
Show Gist options
  • Save partyka1/a69c86d9d36f955947f45a129196e63d to your computer and use it in GitHub Desktop.
Save partyka1/a69c86d9d36f955947f45a129196e63d to your computer and use it in GitHub Desktop.

Example implementation of RequiredTrueValidator that can be used on custom checkbox component. Angular has a bug that prevents such custom checkboxes from being required validated properly (angular/angular#17495). In following example <app-checkbox-field> is a name of my custom checkbox field which implements ControlValueAccessor

import {Directive, Input} from '@angular/core';
import {AbstractControl, NG_VALIDATORS, Validator} from '@angular/forms';
@Directive({
selector: 'app-checkbox-field[required]',
providers: [{provide: NG_VALIDATORS, useExisting: RequiredTrueDirective, multi: true}]
})
export class RequiredTrueDirective implements Validator {
// tslint:disable-next-line:no-input-rename
@Input() required: boolean | string;
validate(control: AbstractControl): { [key: string]: any } | null {
/**
* Covering cases:
* <app-checkbox-field required></app-checkbox-field> // in this case this.required is empty string ""
* <app-checkbox-field [required]="true"></app-checkbox-field> // in this case this.required is boolean `true`
**/
if (this.required || this.required === '') {
return control.value + '' !== 'true' ? {
appRequiredTrue: {
message: 'Field required',
value: control.value
}
} : null;
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment