【问题标题】:Conditional @HostBinding depending on @Input()有条件的 @HostBinding 取决于 @Input()
【发布时间】:2017-12-08 23:09:44
【问题描述】:

我正在尝试使用 @HostBinding 将 CSS 类 foo 绑定到我的主机组件,具体取决于我对 dynamic 变量所做的测试。 但无法使其正常工作。
这是我已经尝试过的:

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

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

    constructor() {
    }

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

我怎样才能让它工作?我可能在想办法听input的变化?

【问题讨论】:

    标签: angular typescript angular2-hostbinding


    【解决方案1】:

    试试这个方法。制作@Input 属性getter/setter 并从setter 中设置isFoo

    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() {
            }
        }
    

    【讨论】:

    • 像魅力一样工作(就像 Skeptor 的回答一样)。谢谢大家!
    【解决方案2】:

    你所做的几乎是正确的:

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

    【讨论】:

    • 虽然我发现这个解决方案看起来更惯用,但它似乎不起作用。使用 get 函数时,该类将始终被设置。
    • 此解决方案可能会导致性能问题。 isFoo 将在每个更改检测周期进行评估,因为它是一个 getter,Angular 无法知道其值是否已更改。 @Yordan 的回答解决了这个问题。
    猜你喜欢
    • 2018-01-11
    • 1970-01-01
    • 2017-09-24
    • 2012-01-13
    • 2014-06-08
    • 2010-11-15
    • 1970-01-01
    • 2015-12-18
    • 1970-01-01
    相关资源
    最近更新 更多