【问题标题】:Ionic 3 Directive. Add Custom Property on Div?离子 3 指令。在 div 上添加自定义属性?
【发布时间】:2018-11-19 19:03:29
【问题描述】:

我正在尝试绑定到自定义 div 属性 data-disqus-identifier

<div class="disqus-comment-count" [data-disqus-identifier]="project.route"></div>

我为此创建了一个指令

import { Directive, Input } from '@angular/core';

@Directive({
  selector: '[div]',
  exportAs: 'data-disqus-identifier',
})
export class DisqusCountDirective {

  @Input('data-disqus-identifier') identifier: string;

  constructor() { }

}

它已正确导入 app.module.ts 但我收到以下错误...

Can't bind to 'data-disqus-identifier' since it isn't a known property of 'div'.

任何帮助表示赞赏。

谢谢

【问题讨论】:

    标签: angular ionic-framework binding ionic3 directive


    【解决方案1】:

    您需要在此处使用Attribute Directive。所以你的代码会是这样的:

    在您的 HTML 中:

    <div class="disqus-comment-count" disqusCount [data-disqus-identifier]="project.route"></div>
    

    在您的 Typescript 中(例如 disqus-count.directive.ts):

    import { Directive, Input } from '@angular/core';
    
    @Directive({
      selector: '[disqusCount]'
    })
    export class DisqusCountDirective {
    
      @Input('data-disqus-identifier') identifier: string;
    
      constructor() { }
    
    }
    

    【讨论】:

    • 好吧,这停止了错误。它现在显示为 ng-reflect-identifer,我相信要使其正常工作,它需要是 data-disqus-identifier
    • 只是为了清理,为什么不从data-disqus-identifier 中删除data- 以避免与数据属性发生任何潜在冲突,并且只是为了更普遍地分离关注点。如果某些 Disqus 插件需要 data 属性,您可以在 typescript 中与该插件进行交互吗?
    猜你喜欢
    • 2015-06-13
    • 1970-01-01
    • 1970-01-01
    • 2011-08-03
    • 2013-10-17
    • 1970-01-01
    • 1970-01-01
    • 2012-07-10
    • 1970-01-01
    相关资源
    最近更新 更多