Chris Sheppard February 2016

Can you have a stand alone directive in Angular 2

I'm playing around with Angular 2, What I'd like to do is to have a stand alone directive directly assigned to an element within the HTML. Is this possible?

Directive:

import {Directive, ElementRef} from 'angular2/core';
@Directive({
    selector: '[Slidernav]'
})
export class Slidernav {
    constructor(private element: ElementRef) {
        console.log('Slider Run');
    }
}

and I would assign it to any HTML element like so:

<div slidernav>Some content</div>

The reason why I'm asking is because I don't want to set the template with HTML that already exists in the DOM using a Component.

EDIT

So based on the responses, this is the component

Component Slider

 import {Component, View, ElementRef} from 'angular2/core';
 @Component({
    selector: 'Slider',
    template: '<ng-content></ng-content>'
 })
 export class Slider {
     constructor(private element: ElementRef) {
         console.log('Slider');
     }
}

index.html

<Slider>
    <div>hello world</div>
</Slider>

I would be expecting the Div to remain within Slider with the content hello world. AFAIK that's how it should work based on what i've been reading about Transclusion. But the console error is:

Error: The component Slider has 1 <ng-content> elements, but only 0 slots were provided.

Answers


Günter Zöchbauer February 2016

Should work except that Angular templates are case sensitive

selector: '[Slidernav]'
...
<div slidernav>Some content</div>

should either be

selector: '[Slidernav]'
...
<div Slidernav>Some content</div>

or

selector: '[slidernav]'
...
<div slidernav>Some content</div>

besides that you might want to use a component with a template like

template: '<ng-content></ng-content>`

This way your component just displays the HTML the parent provided as children to your component

Post Status

Asked in February 2016
Viewed 1,650 times
Voted 11
Answered 1 times

Search




Leave an answer