-
-
Notifications
You must be signed in to change notification settings - Fork 110
Open
Description
I'm using NgxControlValueAccessor in an Angular component to manage the value of a custom input field. However, I am unable to access the value in the ngOnInit and ngAfterViewInit lifecycle hooks. The value is always undefined when I try to log it in these hooks.
Here is the code I have implemented:
import { Component, inject } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import { NgxControlValueAccessor } from 'ngxtension/control-value-accessor';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
console.clear();
@Component({
selector: 'custom-input',
hostDirectives: [NgxControlValueAccessor],
template: `
<label>
<b>Custom label</b>
<input
type="text"
(input)="cva.value = $event.target.value"
[value]="cva.value$()"
[disabled]="cva.disabled$()"
(blur)="cva.markAsTouched()"
/>
</label>
`,
standalone: true,
})
export class CustomInput {
protected cva = inject<NgxControlValueAccessor<string>>(
NgxControlValueAccessor
);
ngOnInit() {
console.log({ ngOnInit: this.cva.value }); // undefined
}
ngAfterViewInit() {
console.log({ ngAfterViewInit: this.cva.value }); // undefined
}
}
@Component({
selector: 'app-root',
imports: [CustomInput, FormsModule, ReactiveFormsModule],
template: `
<custom-input [(ngModel)]="foo" />
`,
})
export class App {
name = 'Angular';
foo = 'hello';
}
bootstrapApplication(App);Steps to Reproduce:
- Clone the [stackblitz project](https://stackblitz.com/edit/stackblitz-starters-mnbvmheo?file=src%2Fmain.ts).
- Check the
ngOnInitandngAfterViewInitlogs in theCustomInputcomponent. - The value of
cva.valueisundefinedin both lifecycle hooks.
Expected Behavior:
I would expect the value of cva.value to be available in ngOnInit or ngAfterViewInit, or that Angular provides a way to access it within these hooks.
Additional Information:
- The
cva.valueshould reflect the value bound to the[(ngModel)]in the parent component. cvais injected correctly, but the value isn't accessible during the initialization lifecycle.
Possible Workaround:
Are there any specific lifecycle hooks or techniques for retrieving the value in ngOnInit or ngAfterViewInit?
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
No labels