【问题标题】:Dynamic Property Binding for Angular Directive InputsAngular 指令输入的动态属性绑定
【发布时间】:2021-05-21 12:45:18
【问题描述】:

您好,我正在制作一个拖动指令,但由于它的工作方式,我无法让它在动态对象上工作,因为它在输入中调用了 id。

@Input()
set Drag(options: any) {
   this.stickerElement = document.getElementById(options.id);
}

当元素不是动态的时候效果很好:

<div id="sticker" class="issues" [Drag]="{id: 'sticker'}">

但是当它被动态设置时,我无法弄清楚如何动态插入 ID。

<div [attr.id]="'Session' + Day.id" [Drag]="{id:'Session' + Day.id}"></div>

当您使用它时,我尝试使用 @HostListener 设置 this.stickerElement,但这允许指令冒泡并使用子元素。我想我可以解决它,但它感觉不对。

我觉得我错过了一些知识,因为无论我在谷歌上搜索什么,关于如何正确插入它都没有任何有用的信息。你能把一个属性插入到这样的指令中吗?

提前致谢 乙

【问题讨论】:

    标签: javascript angular angular-directive directive


    【解决方案1】:

    我认为插值没有任何问题。然而,Angular 中的document.getElementById(options.id) 看起来很脏。相反,您可以使用template reference variable 并直接发送HTMLElement

    试试下面的

    模板

    <div appSticker #sticker [Drag]="{ref:sticker}"></div>
    

    指令

    @Directive({ selector: "[appSticker]" })
    export class StickerDirective {
      stickerElement: HTMLElement;
    
      @Input()
      set Drag(options: any) {
        this.stickerElement = options.ref;
      }
    
      constructor() {}
    }
    

    另外,我在您的代码中的 &lt;div&gt; 标记中看不到指令绑定。

    【讨论】:

      猜你喜欢
      • 2016-08-14
      • 2014-02-14
      • 2018-05-15
      • 1970-01-01
      • 2020-03-22
      • 1970-01-01
      • 2018-07-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多