gpt4 book ai didi

具有多个值的 Angular 6 HostBinding?

转载 作者:行者123 更新时间:2023-12-05 09:16:31 25 4
gpt4 key购买 nike

我已在我的 Angular 6 应用程序中成功使用 @HostBinding 将属性应用于主机组件,就像在变量为真时应用类一样:

@HostBinding('class.compact-ui') isCompact;

但是,现在我需要根据选择菜单的模型分配 4 个可能的类之一。例如,用户可以选择 redbluegreen

我想我可以在任何颜色为真时使用多个主机绑定(bind):

@HostBinding('class.green-ui') uiColor === 'green';

但这似乎是错误的。执行此操作的正确方法是什么?

最佳答案

要将多个类分配给主机,您可以这样做:

@HostBinding('class') classAttribute: string = 'classA classB';

对于您的情况,您可以这样做:

@HostBinding('class') classAttribute: string;

// Example function that updates the classAttribute property
// You might handle it differently in your application
updateClassAttribute(color: string, isCompact: boolean) {
const classes: string[] = [`${color}-ui`];

if (isCompact) classes.push('compact-ui');

this.classAttribute = classes.join(' ');
}

注意上面的函数逻辑可以写在一行中,像这样:

this.classAttribute = [ ...isCompact ? ['compact-ui'] : [], `${color}-ui` ].join(' ');

此外,如果您希望为这些值(isCompactcolor)使用 Redux 存储(例如 @ngrx/store)在您的应用程序的多个位置需要它们。

关于具有多个值的 Angular 6 HostBinding?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50356466/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com