Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2: how to conditionally apply attribute directive?

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>
like image 633
Peter Avatar asked May 04 '16 07:05

Peter


People also ask

How do you conditionally apply a directive?

Currently, there is NO way to conditionally apply a directive to a component. This is not supported. The components which you have created can be added or removed conditionally. There is already an issue created for the same with angular2 , so it should be the case with angular4 aswell.

What are the attribute directives in Angular 2?

The attribute directive changes the appearance or behavior of a DOM element. These directives look like regular HTML attributes in templates. The ngModel directive which is used for two-way is an example of an attribute directive.

What is restrict option in directive?

Directive comes with many Directive Definition Objects (DDO). From them restrict is one. Using restrict option inside a Custom Directive we can prevent the access level of Directive for Element(E), Attribute(A), Comment(M) or Class(C).

What is the use of attribute directive in Angular?

Attribute directives listen to and modify the behavior of other HTML elements, attributes, properties, and components. Adds and removes a set of CSS classes. Adds and removes a set of HTML styles. Adds two-way data binding to an HTML form element.


1 Answers

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.

like image 67
Günter Zöchbauer Avatar answered Oct 31 '22 21:10

Günter Zöchbauer