tt9
tt9

Reputation: 6069

How can I pass non-string values to a HostListener function in Angular?

I have a directive that goes on an input element, and in the directive class I want to listen to blur and focus on the same function. On each of these events I'd like to pass a literal boolean value but the args array is of type string[]

How would I modify this function to accept booleans or any other type for that matter

@HostListener('focus', ['true'])
@HostListener('blur', ['false'])
private onFocusChanged(isFocused: boolean) {

   // Implementation...

   // Both events fire the function but the blur passes true instead of false.

}

Upvotes: 1

Views: 1101

Answers (2)

Estus Flask
Estus Flask

Reputation: 222840

args array consists of expressions, this is the reason it is string[]. They are expressions because elements are supposed to be $event, $event.target, etc. strings.

Any non-string value can be used instead of a string, as long as it can be coerced to a valid expression string (booleans can) and comply with TypeScript type checking.

Both

@HostListener('focus', [<string><any>true])
@HostListener('blur', [<string><any>false])
private onFocusChanged(isFocused: boolean) { ... }

and

@HostListener('focus', ['true'])
@HostListener('blur', ['false'])
private onFocusChanged(isFocused: boolean) { ... }

are equivalent and result in a callback being called with boolean true on one event and false on another.

Upvotes: 1

tt9
tt9

Reputation: 6069

As a temporary solution, I have implemented two separate HostListeners which call the main handler function with the desired boolean value as such:

  @HostListener('focus')
  private _onFocus() {
    this.onFocusChanged(true);
  }

  @HostListener('blur', [])
  private _onBlur() {
    this.onFocusChanged(false);
  }

I think it would be valuable to know if the code in the original question can be modified to achieve this effect for cutting down on boilerplate code, so I'll accept the answer that makes it work as it was asked or shows that what I was originally trying to do is not possible.

Upvotes: 0

Related Questions