Muthukumar
Muthukumar

Reputation: 9599

Angular Custom Form Control - Get default value

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 ?

Upvotes: 1

Views: 1955

Answers (1)

Ashish Ranjan
Ashish Ranjan

Reputation: 12960

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.

Upvotes: 3

Related Questions