I have a custom angular checkbox, based on using the ControlValueAccessor
interface.
This, on itself works well and the checkbox get's displayed as required.
What I would like to achieve is when the @Input() showChanges: boolean = true
that the CSS gets adjusted to the display the box in a different color.
However, in the component -with the ControlValueAccessor- there is no property .dirty
that is accessible? The idea would be that I can set the showDirty
option externally and that the checkBox internals verifies if the status is indeed dirty
So in HTML where the component is used
<app-checkbox
[showDirty]="true"
[formControl]="checkBox"></app-checkbox>
And subsequently in the CheckBoxComponent
@Input() showDirty: boolean = false;
get dirty(): boolean {
return (this.dirty && this.showDirty) //nothing available for 'this.dirty'?
}
But for some reason I do not have access to the FormControl
interface?
I have tried by extending the FormControl
class but that doesn't work...
CodePudding user response:
The ControlValueAccessor
interface doesn't have the dirty
property. See the documentation.
interface ControlValueAccessor {
writeValue(obj: any): void
registerOnChange(fn: any): void
registerOnTouched(fn: any): void
setDisabledState(isDisabled: boolean)?: void
}
You can get the dirty
property from the FormControl
. And the FormControl
will be created by the FormGroup
and not by your custom control itself. So like this way:
const nameControl = this.myForm.get('name'); // or this.myForm.controls['name'];
if (nameControl.dirty) {
// ...
}
Here is a Stackblitz example.
CodePudding user response:
I found the solution here: by RITCHIE JACOBS
Solution:
- remove any `provider' entries
- add the constructor as below
import { Component, OnInit, Input, Self, Optional } from "@angular/core";
import { ControlValueAccessor, FormControl, NgControl } from "@angular/forms";
import { v4 as uuidv4 } from 'uuid';
@Component({
selector: "fl-checkbox",
templateUrl: "./fl-checkbox.component.html",
styleUrls: ["./fl-checkbox.component.scss"],
})
export class CustomCheckboxComponent implements ControlValueAccessor, OnInit {
fc!: FormControl
uid: string = uuidv4()
@Input() disabled: boolean = false;
@Input() checked: boolean = false;
@Input() showDirty: boolean = false;
constructor(
@Self()
@Optional()
private ngControl: NgControl
) {
if (this.ngControl) {
this.ngControl.valueAccessor = this;
}
}
onChange: any = () => {};
onTouched: any = () => {};
writeValue(checked: boolean): void {
this.checked = checked;
}
registerOnChange(fn: any): void {
this.onChange = fn;
}
registerOnTouched(fn: any): void {
this.onTouched = fn;
}
setDisabledState?(isDisabled: boolean): void {
this.disabled = isDisabled;
}
ngOnInit(): void {
}
get dirty(): boolean {
const _dirty = <boolean>this.ngControl?.dirty;
return (_dirty && this.showDirty);
}
onModelChange(e: boolean) {
this.checked = e;
this.onChange(e);
this.onTouched();
}
}