Skip to content

NgxControlValueAccessor value is undefined in ngOnInit and ngAfterViewInit #632

@wizardnet972

Description

@wizardnet972

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:

  1. Clone the [stackblitz project](https://stackblitz.com/edit/stackblitz-starters-mnbvmheo?file=src%2Fmain.ts).
  2. Check the ngOnInit and ngAfterViewInit logs in the CustomInput component.
  3. The value of cva.value is undefined in 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.value should reflect the value bound to the [(ngModel)] in the parent component.
  • cva is 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?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions