【问题标题】:How to call linear gradient function in typescript?如何在打字稿中调用线性渐变函数?
【发布时间】:2021-07-14 23:51:07
【问题描述】:

我正在尝试将线性渐变添加到打字稿中的样式变量。像这样的

在component.html中

<div class="colored" [ngStyle]="colorTest3">

在component.ts中

colorTest3 = {
   background-image: linear-gradient(red, yellow)
}

但它一直给我一个错误。帮忙?

【问题讨论】:

  • 添加类 colortest3 并在 scss 文件中添加样式表,而不是在 ts 文件中
  • 你能在问题中包含错误信息吗?
  • @SHUBHAMSINGH 我想稍后动态更改变量它不会保持静态
  • @ConnorsFan 我认为你不能在打字稿中加入破折号,我试过这个backgroundImage: linearGradient(red, yellow) 但它说 找不到名称'linearGradient'
  • @Ruba 假设你想要红色渐变然后添加类 red ,如果你想要绿色然后添加绿色类等。然后在 scss 文件中添加所有 css

标签: css angular typescript angular8


【解决方案1】:

如果您没有用引号括起来,则对象属性名称中不能包含破折号 (-)。值也必须是字符串。

colorTest3 = {
  "background-image": "linear-gradient(red, yellow);"
}

【讨论】:

  • 它有效,但如果我希望函数中有像这样的变量呢`color1="blue"; color2="yellow"; colorTest3={ background-image: linear-gradient(color1, color2) }
  • @RubaSbeih `linear-gradient(${value1}, ${value2})`
【解决方案2】:

&lt;div&gt; 标签你必须添加高度样式以显示线性渐变样式的效果。并确保结束 div 标签。 (&lt;/div&gt;)

在组件.html中

<div class="colored" [ngStyle]="colorTest3">
</div>

在component.ts中

colorTest3 = {
    'background-image': 'linear-gradient(red, yellow)',
    'height': '200px'
   }

【讨论】:

    【解决方案3】:

    试试这个

    colorTest3 = {
      'background-image': 'linear-gradient(red, yellow)'
     }
    

    demo

    【讨论】:

      【解决方案4】:

      如果你只有一种样式要绑定,你可以使用[style.backgroundImage],你也应该在''中添加linear-gradient(red, yellow),就像这样"'linear-gradient(red, yellow)'"

      试试这样:

      <div class="colored" [style.backgroundImage]="'linear-gradient(red, yellow)'">
      

      要获得动态颜色,请尝试如下:

      [style.backgroundImage]="'linear-gradient(' + color1 + ', ' + color2 + ')'"
      

      TS:

      color1 = 'red'
      color2 = 'blue'
      

      【讨论】:

        【解决方案5】:

        对于 html:

        <div [ngStyle]="background"></div>
        

        对于 ts:

        background: any = "linear-gradient('color1', 'color2')"
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-11-27
          • 2017-09-15
          • 1970-01-01
          • 2018-05-18
          • 1970-01-01
          • 1970-01-01
          • 2020-02-21
          • 2023-02-07
          相关资源
          最近更新 更多