arn-arn
arn-arn

Reputation: 1377

How to create an attribute-directive in Angular 2 and bind it to a property?

I want to create a custom attribute-directive and bind this to a property. I plan to retrieve this attribute and get the value later on.

I created a Directive:

@Directive({ 
    selector: '[data-url]' 
})

export class DocumentURL{
    constructor(private el: ElementRef, private renderer: Renderer) { }
}

this is the component that uses the directive:

@Component({
    templateUrl: 'some.component.html',
    directives: [DocumentURL]
})

this is my some.component.html:

<div class="col-xs-6" [data-url]='docUrl' (mouseleave)='onMouseLeave($event)'>

However, it is throwing an error saying that: Can't bind to 'data-url' since it isn't a known native property

Can someone help please? thanks.

Upvotes: 3

Views: 5723

Answers (1)

No&#233;mi Sala&#252;n
No&#233;mi Sala&#252;n

Reputation: 5036

You have to add an @Input property in your directive.

@Directive({ 
    selector: '[data-url]' 
})
export class DocumentURL{

    @Input('data-url')
    dataUrl:string;

    constructor(private el: ElementRef, private renderer: Renderer) { }
}

See plunkr.

Upvotes: 6

Related Questions