Skip to content

hostBinding

Created by Lucas Garcia

hostBinding is a function that returns either a writable or readonly signal and binds the value held in that signal to the host property passed as the first argument like @HostBinding would do.

import { hostBinding } from 'ngxtension/host-binding';

Usage

With @HostBinding you can bind a color from a class property:

@Component({
standalone: true,
selector: 'my-component',
template: '...',
})
export class MyComponent {
@HostBinding('style.color') color = 'red';
updateColor(color: 'red' | 'blue') {
this.color = color;
}
}

With hostBinding you can now bind anything like @HostBinding on writable or readonly signals:

@Component({
standalone: true,
selector: 'my-component',
template: '...',
})
export class MyComponent {
color = hostBinding('style.color', signal('red'));
updateColor(color: 'red' | 'blue') {
this.color.set(color);
}
}

With hostBinding you can update and remove attributes, like @HostBinding.

@Component({
standalone: true,
selector: 'my-component',
template: '...',
})
export class MyComponent {
#ariaHidden = hostBinding('attr.aria-hidden', signal(false));
updateAriaHidden(value: boolean) {
this.#ariaHidden.set(value);
}
}