Why doesn't the ngOnChanges get trigger when you "writeValue" in a ControlValueAccessor ? I am emitting some events via the registerOnChange but I dont see any action in the ngOnChanges
const CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR = new Provider(
NG_VALUE_ACCESSOR, {
useExisting: forwardRef(() => CustomInput),
multi: true
});
@Component({
moduleId: module.id,
selector: 'custom-input',
templateUrl: 'custom-input.html',
styleUrls: ['custom-input.css'],
directives: [CORE_DIRECTIVES],
providers: [CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR]
})
export class CustomInput implements ControlValueAccessor{
private _text: any = '';
public isValid:boolean = false;
onChange: EventEmitter<any> = new EventEmitter();
onTouched: any;
constructor(private ngControl:NgControl) {
}
ngOnChanges(e) {
console.log('ngOnChanges');
}
get text(): any { return this._text; };
set text(v: any) {
if (v !== this._text) {
this._text = v;
this.onChange.emit(v);
}
}
writeValue(v) {
this.text = v;
}
registerOnChange(fn): void {
this.onChange.subscribe(fn);
}
registerOnTouched(fn): void {
this.onTouched = fn;
}
}
ngOnChanges
is called when @Input()
properties change.
Suppose your custom input had a text property:
export class CustomInput implements OnChanges {
@Input() text;
ngOnChanges() {
console.log('ngOnChanges');
}
}
Then ngOnChanges
will be called when someVariable
changes:
<custom-input [text]="someVariable"></custom-input>
Changes made from within the component do not trigger the callback. ngOnChanges
is purely for Inputs.
https://angular.io/guide/lifecycle-hooks#lifecycle-sequence
Note: ngOnChanges
is also called before ngOnInit
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With