Angular 2: how to conditionally apply attribute directive?

久未见 提交于 2019-12-18 08:39:56

问题


I use drag&drop via ng2-dragula. The drag&drop functionality is applied this way:

<div class='container' [dragula]='"first-bag"'>
    <div>item 1</div>
    <div>item 2</div>
</div>

If I understand angular 2 properly, the way how [dragula]='"first-bag"' is attached to my div is called Attribute Directive in Angular 2.

Now I have a variable in my component called enableDragNDrop:boolean. How can I use this variable to attach [dragula]='"first-bag"' to my div only when enableDragNDrop == true ?

If enableDragNDrop == false, i want this:

<div class='container'><!-- no dragula attribute directive, no dragndrop -->
    <div>item 1</div>
    <div>item 2</div>
</div>

回答1:


There is no way to dynamically add/remove directives by adding/removing a selector. The selector dragula has to be static HTML for the directive to get applied. You can only use features of dragula to enable/disable it if it provides such a configuration option.

I haven't used ng2-dragula or dragula but I guess you can assign a dragModel and configure it this way

<div class='container' dragula [dragulaModel]="dragulaModel">
dragulaModel = {start: function () {}};

and when you want to enable it, assign a model that doesn't disable start

enableDrag() {
  this.dragulaModel = {};
}

Not tested, just skimmed a bit through the source.



来源:https://stackoverflow.com/questions/37021355/angular-2-how-to-conditionally-apply-attribute-directive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!