【问题标题】:Angular : Using pipe inside ts not in htmlAngular:在 ts 中使用管道而不是在 html 中
【发布时间】:2019-12-16 08:06:37
【问题描述】:

我有一个管道,它根据来自数据 json 的值返回一个 css 字符串。

主要组件

this.coords.push(new L.Marker([i.lat, i.lng], {
  rotationAngle: i.heading,
  rotationOrigin: 'bottom center',
  icon: new L.DivIcon({
    html: `<div style="width: 65px;";>
             <img src="assets/icon/airplan.jpg" style="width: 20px;height: 25px;" ngClass='${i.heading}| heading'/>
           </div>`
  })
}).addTo(this.map)

问题是当我运行我的项目时,我只得到相同的管道名称输出,我的意思是看起来管道不起作用! 输出

<img src="assets/icon/airplan.jpg" style="width: 20px;height: 25px;" ngclass="272|heading">

有什么建议

【问题讨论】:

  • 如果它在 TS 中,为什么不直接使用函数而不是管道?类似&lt;img src="assets/icon/airplan.jpg" style="width: 20px;height: 25px;" ngClass='"+this.calcHeading(i.heading)+"'/&gt;
  • 因为标题的值是数字,而且你知道 css 不是像 .12{} 这样的接受数字
  • 这能回答你的问题吗? Is it possible to use a pipe in the code?
  • This 也很有帮助。
  • 也许还发布管道的代码,因为您说它返回 css,在这种情况下考虑使用[ngStyle]。另请注意,[ngClass][ngStyle] 期望将对象作为值。喜欢[ngStyle]="{'width': someVar}"

标签: angular pipe


【解决方案1】:

您是否尝试过使用不带${} 括号的ngClass

[ngClass]='i.heading | heading'

否则你可以在组件类中运行管道:

您可以在构造函数中注入管道并运行转换函数

@Component({...})
export class MyComponent {
  constructor(private headingPipe: HeadingPipe) {}

  transformedHeading(heading: string) {
    return this.headingPipe.transform(heading);
  }
}

在你的模板中

<img [ngClass]="transformedHeading(i.heading)"/>

【讨论】:

  • @AliGhassan ngClass 不会工作,因为 Angular 不会渲染那部分代码。取而代之的是Leaflet 自行注入该模板..
  • 谢谢。你救了我 。 css 类的名称现在显示在 nglcass 中,但他不适用。知道为什么吗?见图片 [i.ibb.co/QP1X3gY/Capture.png]
  • 您可以尝试将[ngClass] 替换为class 吗?也请去掉方括号。
【解决方案2】:

那是因为您使用ngClass='...' 而不是[ngClass]='...'

对于前者,您的字符串会按原样传递而无需评估。使用后者(使用[]),您的语句实际上已被评估 - 并且管道将被考虑在内。

【讨论】:

  • 我以前做过,但还是同样的问题
  • 那么你的管道没有被导入到组件的模块中
【解决方案3】:

这样使用

<img src="assets/icon/airplan.jpg" style="width: 20px;height: 25px;" [ngclass]="272|heading">

现在管道会返回你想要的。

【讨论】:

    猜你喜欢
    • 2017-01-31
    • 2022-07-24
    • 2020-10-28
    • 2021-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-18
    • 1970-01-01
    相关资源
    最近更新 更多