Apr 6, 2017

Angular 2 Directive

Directive change appearance or behavior of the element. Component is an element and directive is attribute. It is defined similar as component, in place of @Component you use @Directive. Also notice selector is wrapped with [] which indicates its an attribute.

@Directive({
selector: "[my-directive]",
})

Within directive you can get reference of the element like this

private el: HTMLElement;
        @Input("modal-trigger") modalId: string; //you need to wrap modal-trigger in "" as it has - which is not allowed in variable name

        constructor(ref: ElementRef) {
               this.el = ref.nativeElement;
        }

Now finally you can add this directive to any of the element
<some-element my-directive="some-data-to-be-passed">

No comments:

Post a Comment