Angular 2:带有Input对象属性的@HostBinding

时间:2017-08-03 14:05:19

标签: angular angular2-hostbinding

是否可以像这个例子一样绑定@HostBinding值?

@Input() user: User;
@HostBinding("class.temp") user.role == "Admin"

我知道我可以这样做:

private _user: User;
@Input() set user(user: User) {
    this._user = user;
    this.temp = (this._user.role == "Admin");
}
@HostBinding("class.temp") temp: boolean;

但在这种情况下,如果我的用户更改了他的角色,则该组件中的值永远不会更新。这该怎么做 ?

1 个答案:

答案 0 :(得分:5)

这是我对对象属性进行主机绑定的方法:

@Input()
public user: User;

@HostBinding('class.example')
public get isExample(): boolean {
     return this.user && this.user.role === 'admin';
}

如果您发现自己陷入困境,只需要让功能正常运行。您可以使用DoCheck界面检查每次更改检测的角色更改。这告诉Angular为每次更改检测调用ngDoCheck

@Input()
public user: User;

@HostBinding('class.example')
public isExample: boolean;

public ngDoCheck(): void {
     this.isExample = this.user && this.user.role === 'admin';
}

以上增加了应用程序的开销,并不是最佳实践。

您应该将输入分为Userrole,如下所示:

@Input()
public user: User;

@Input()
public role: string;

@HostBinding('class.example')
public get isExample(): boolean {
    return this.role === 'admin';
}

这是最简单的解决方案。因为它使用Angular自己的变化检测。

另一种解决方案是使user对象不可变。这样,每次更改属性时都会创建一个新的用户对象。这也将触发Angular中的变化检测,并且是在绑定中处理对象的首选方法。

话虽如此,不可改变有限制,并且可能是一种痛苦。

还有其他解决方案,例如自定义可观察对象,并使用ChangeDetectRef告诉组件某些内容已发生变化。这些解决方案涉及更多,我认为组件应该保持简单。

我尝试遵循原语绑定规则。其中组件的所有输入都是类型编号或字符串。避免数组和对象。

在您的示例中,您的组件是否真的需要完全访问用户对象或其中一些属性?如果您为所需的每个属性添加输入,那么您已将组件与用户对象分离,这样也可以更轻松地进行测试。