Using Angular Signals with HostBinding to update style?

230 Views Asked by At

In a app-test component I have the following:

  @Input( { transform: booleanAttribute})
  reverse: boolean = false;

  @HostBinding('style.flex-direction')
  direction: string = this.reverse ? 'column-reverse' : 'column';

And so if the designer applies the reverse attribute to app-test like this:

<app-test reverse></app-test>

Then Angular should set style="flex-direction: column-reverse" on the app-test element.

And I'm wondering how to use Angular signals so that when reverse is set to true, direction will be set to column-reverse. Thoughts?

3

There are 3 best solutions below

0
Matthieu Riegler On BEST ANSWER

This is being discussed in this issue. Currently the combination of @HostBinding and signals is not supported.

The workaround for this is to use a getter:

reverse = input.required<boolean>();

@HostBinding('attr.style.flex-direction')
get direction() { return this.reverse() ? 'column-reverse' : 'column' }
0
Benny Halperin On

You can do the following:

@Component({
  selector: 'app-child',
  standalone: true,
  template: 'My name (red is {{ red() }})',
})
export class AppChildComponent {
  red = input(false);

  @HostBinding('style.color')
  get color() {
    return this.red() ? 'red' : 'green';
  }
}

And in the container component:

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [AppChildComponent],
  template: `
    <app-child [red]="true"></app-child>
  `,
})
export class App {
}

Working example here

0
Ole On

My current project was on Angular 16, so this is what I ended up with (Since input is for Angular 17+):

  @Input( { transform: booleanAttribute})
  reverse:boolean = false;

  @HostBinding('style.flex-direction')
  get direction() { return this.reverse ? 'column-reverse' : 'column' }