Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional @HostBinding depending on @Input()

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 ?

like image 836
Alexis Facques Avatar asked Jul 05 '17 10:07

Alexis Facques


2 Answers

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';
    }

}
like image 103
Vamshi Avatar answered Oct 31 '22 03:10

Vamshi


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() {
        }
    }
like image 38
Yordan Nikolov Avatar answered Oct 31 '22 03:10

Yordan Nikolov