1

I have a custom control which uses “ControlValueAccessor” - “registerOnChange” callback to send the value to the parent form whenever the value of the form control changes. No problem here.

But I also want to send the default value which I set for the custom control during OnInit. The problem is the “registerOnChange” callback happens only after OnInit.

Is there a way around ?

2
  • You already have default value as you are setting it up. Why can't you use that? Commented Apr 25, 2019 at 7:54
  • Doesn't the added answer solve your issue? Commented Apr 26, 2019 at 10:05

1 Answer 1

3

ngAfterViewInit() will be called after the registerOnChange method runs.

You can programatically set the value of the input here but that would not call the registered onChange() method(say the name is onChange). You will need to explicitly call it. Now the problem comes by the " ExpressionChangedAfterItHasBeenCheckedError".

The problem is the check can happen in the parent component too if there are bindings to the child control there. Calling a detectCahnges() will only check the changes in the current component and its children. Doing a markForCheck() will mark this and its ancestors for check in next change detection but will not call change detection immediately. If nothing helps, a setTimeout() will definitely.

You can have something like:

  ngAfterViewInit() {
    setTimeout(() => {
      this.value = "changed value";
      this.onChange(this.value)
    })
  }


<input 
  [value]="value"
  (input)="onChange($event.target.value)"
  (blur)="onTouched()"
  [disabled]="isDisabled"
  type="text">

See an example here: https://stackblitz.com/edit/controlvalueaccessorgeneric-srsut9?file=src/app/app.component.ts

But again, why do you need to do this? You can always give the initial form control values while you are initializing the Reactive form.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. I am handling it with setTimeout as you have suggested. I need it, as my custom control inherently have a value even if not getting initialised
@Muthukumar Got it! Thank you for accepting the answer! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.