Conditional @HostBinding depending on @Input()
Asked Answered
D

2

14

I'm trying to bind the CSS class foo to my host component, using @HostBinding depending on a test I do on a dynamic variable. But can't manage to make it work properly.
Here's what I already tried:

export class MyComponent {
    @Input()
    public input: string;

    @HostBinding('class.foo')
    public isFoo: Boolean = this.inputIsCorrect();

    constructor() {
    }

    private inputIsCorrect(){
        return (this.input != 'not correct');
    }
}

How I could make it work ? I was maybe thinking of way to listen to input changes ?

Deepfry answered 5/7, 2017 at 10:23 Comment(0)
P
15

Try this way. Make @Input property getter/setter and set the isFoo from the setter.

export class MyComponent {   
     @Input()
        public get input (): string {
          return this._input;
        }
        public set input (val: string) {
          this._input = val;
          // when the input is set check it and set isFoo;
          this.isFoo = (val != 'not correct');
        }

        @HostBinding('class.foo')
        public isFoo: Boolean = false; // false is init value

        constructor() {
        }
    }
Prima answered 5/7, 2017 at 10:28 Comment(1)
Works like a charm (just as Skeptor's answer). Thanks guys !Deepfry
S
8

What you did is almost correct :

export class MyComponent {
    @Input()
    public input: string;

    @HostBinding('class.foo')
    public get isFoo(): Boolean {
        return this.input !== 'not correct';
    }

}
Salvatoresalvay answered 5/7, 2017 at 11:37 Comment(2)
Although I find this solution to appear more idiomatic, it doesn't seem to work. The class, when using a get function, will always be set.Dariusdarjeeling
This solution might cause performance issues. isFoo will be evaluated on each change detection cycle since it is a getter and Angular can't know if its value has changed. @Yordan's answer solves this issue.Shelter

© 2022 - 2024 — McMap. All rights reserved.