Bryant11
Bryant11

Reputation: 333

Style host component based on model property

I know about the different class approaches that you can take and the :host selector, however I want to apply conditional hosting based on a property that I have in my component class.

Let say I have

@Input('val') val: string;

Then based on that input I calculate the height of the element and want to apply it via the host configuration of the @Component. How do I do that?

I know a workaround using ElementRef and apply the styling with regular JavaScript, but I am not really happy with that approach, so I am looking for "the angular approach".

I am really struggling here with the lack of documentation on the Angular site and the total absence of real world examples.

Upvotes: 0

Views: 171

Answers (2)

yurzui
yurzui

Reputation: 214047

I think that you can write something like this

  @Input('val') val: string;
  @HostBinding('style.height') get height {
    return this.val + 'px';
  }

See an example here https://plnkr.co/edit/kNSjCFG710xsCUiiBxat?p=preview

Upvotes: 1

Thierry Templier
Thierry Templier

Reputation: 202176

You could use the @HostBinding decorator like this:

@Input('val') val: string;
@HostBinding('attr.width')
width:string;

ngAfterViewInit() {
  this.width = this.val + 'px'; // for example
}

Upvotes: 1

Related Questions