【问题标题】:How to apply multiple object property to ngStyle如何将多个对象属性应用于 ngStyle
【发布时间】:2022-01-10 02:11:56
【问题描述】:

我的 HTML 中有一个元素,如下所示: <span [ngStyle]="{'background': getColor(selectedOption.type)}">BLAH</span>

我的 TS 文件中有这样的条件:

public getColor(type: string){

        switch (type) {
        case 'General':
            return {background: '#ffe5d7', color: '#e7560a' };
        case 'Interview':
            return { background: '#ffe5d7', color: '#e7560a' };
//more code

基本上,如果用户选择“常规”,我希望从函数返回正确的背景和字体颜色,并使用 ngStyle 将其应用于元素。但这不能正常工作。我做错了什么?

【问题讨论】:

  • 尝试 BLAH 或从您的退货声明中删除背景。因为您要复制背景两次。同样,您还应该从 return 中删除括号

标签: angular ng-style


【解决方案1】:

试试这个:

<span [ngStyle]="getColor(selectedOption?.type)">BLAH</span>

public getColor(type: string | undefined){

   if (type) {

      switch (type) {
        case 'General':
            return {background: '#ffe5d7', color: '#e7560a' };
        case 'Interview':
            return { background: '#ffe5d7', color: '#e7560a' };
        //more code

        case default:
            return {};
 
   }

return {};
}

  

编辑:我刚刚读到@Onur Baştürk 在我面前回答。 他是对的,你在复制 background 属性, 一个在 HTML ([ngStyle]="{'background':...) 中,另一个在您的 ts 代码中:

return {background: '#ffe5d7', color: '#e7560a' ....

【讨论】:

  • 这不起作用。我收到此错误:键入'{背景:字符串;颜色:字符串; } | undefined' 不能分配给类型 '{ [klass: string]: any; } |空值'。类型 'undefined' 不能分配给类型 '{ [klass: string]: any; } |空'。
  • 我刚刚编辑了我的答案。您的交换机中有“默认”情况吗?如果没有,请按照我在编辑代码中所做的那样添加它。并照顾新的“?”。我放入了 html 代码,以及“if (type)”
  • 另外,请注意这个答案正确使用了 ngStyle。在 OP 中指定使用 ngClass 是不正确的,因为它需要一个 Record&lt;cssClassName, booleanish&gt; 对象。
猜你喜欢
  • 2021-09-01
  • 1970-01-01
  • 2015-12-08
  • 2023-01-20
  • 2017-11-05
  • 2020-04-09
  • 1970-01-01
  • 2017-11-17
  • 2019-09-12
相关资源
最近更新 更多