1

Working on a custom input component with ControlValueAccessor and cannot find guidance on the best way to access the input value. Since passing $event is a dubious practice is there a way to trigger two or more methods when an event is fired?

<input type='text' (input)="onChange($event.target.value); watchCity($event.target.value)" [disabled]="disabled" (onEnter)="onEnter($event)" (blur)="onTouched()"  />

Maybe there is a better way to get the value from inside the ControlValueAccessor component?

2
  • 1
    Just to note: passing $event is not dubious as a rule. It's dubious in their example because in the event handling method, they access event.target and that method thus knows too much intricacies of the template. Commented Feb 18, 2019 at 23:28
  • I adjusted my answer accordingly. Commented Feb 18, 2019 at 23:29

1 Answer 1

3

The syntax you have should work, but it is not very common.

You can call one function that calls both of the others.

HTML

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

Component

  onChange(value) {
    // do whatever else
    this.watchCity(value);
  }

Stackblitz is here: https://stackblitz.com/edit/angular-9wqhjp

Also, looking here: https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement I don't see an onEnter event for an input element?

And you mentioned something about a ControlValueAccessor. Are you trying to build one? If so, check out this: https://alligator.io/angular/custom-form-control/ for an example.

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

1 Comment

Thank you for your wonderful comment! Yes delegating the value from one method was the key for me. Thank you again.

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.