angular icon indicating copy to clipboard operation
angular copied to clipboard

Wrong usage of HostBinding in example code

Open karnkumar123 opened this issue 1 year ago • 6 comments

Which @angular/* package(s) are the source of the bug?

core

Is this a regression?

No

Description

getter method is missing in hostbinding examples here https://angular.dev/guide/components/host-elements

Please provide a link to a minimal reproduction of the bug

https://angular.dev/guide/components/host-elements

Please provide the exception or error you saw

No response

Please provide the environment you discovered this bug in (run ng version)

Angular18

Anything else?

No response

karnkumar123 avatar Sep 21 '24 10:09 karnkumar123

The tabindex indeed doesn't change if @HostBinding decorates a method rather than a getter. And I've always wondered why. If the same method is used as the value of a host metadata instead, it works fine. See https://stackblitz.com/edit/stackblitz-starters-pwbb92?file=src%2Fmain.ts

jnizet avatar Sep 21 '24 15:09 jnizet

@jnizet I looked into this and I think it is because of change detection. Getters are evaluated as part of Angular’s change detection cycle. However, when you use @HostBinding with a method, Angular doesn’t automatically call the method during change detection, so it can’t update the host element based on the method’s return value.

jdegand avatar Sep 22 '24 17:09 jdegand

@jdegand Sure, but I wonder why it doesn't do it.

jnizet avatar Sep 22 '24 18:09 jnizet

I think tabindex is a considered an attribute and not a property. Even if you manually trigger change detection with ChangeDetectorRef and call detect changes or mark for check inside update, it won't work because you can't bind to tabindex. You have to use @HostBinding('attr.tabIndex').

jdegand avatar Sep 22 '24 19:09 jdegand

Nope: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/tabIndex.

jnizet avatar Sep 22 '24 19:09 jnizet

Well, it is both an attribute and a property. When you reference the HTML template, it is considered an attribute. For the TypeScript code, it is considered a property.

Check out this issue for further distinction between @Attribute and @HostBinding.

jdegand avatar Sep 22 '24 19:09 jdegand

The root issue is that HostBindings must be properties or getters as their value isn't invoked. I've sent it #63509 to update the guide.

JeanMeche avatar Aug 31 '25 13:08 JeanMeche

This issue has been automatically locked due to inactivity. Please file a new issue if you are encountering a similar or related problem.

Read more about our automatic conversation locking policy.

This action has been performed automatically by a bot.