Reputation: 2784
has anyone created any sample Angular Directive using @Directive
decorator? I searched a lot on however all developers so far created component directives. Even Angular API Review doesn't speak more on this.
Upvotes: 15
Views: 4948
Reputation: 2702
As per Angular2 docs, directives are used to change the behaviour of the DOM element.
Lets create one directive which would change the backgroundcolor of the div to red in case of mouseenter and yellow in case of mouseleave.
Step 1: Create Component
import {Component} from '@angular/core';
@Component({
selector: 'my-comp',
template: '<div colorFlip>This is just a Demo!</div>'
})
export class MyComp {}
Step 2: Create Directive
import {Directive, HostListener, ElementRef} from '@angular/core';
@Directive({
selector: '[colorFlip]'
})
export class ColorFlip {
constructor(private el: ElementRef) {}
@HostListener('mouseenter') handleMouseEnter() {
this.flipColor('red');
}
@HostListener('mouseleave') handleMouseEnter() {
this.flipColor('yellow');
}
flipColor(color:string) {
this.el.nativeElement.style.backgroundColor = color;
}
}
Step 3: Register Directive
@NgModule({
imports: [...],
declarations: [MyComp , ColorFlip ]
})
Upvotes: 0
Reputation: 2337
Here's a sample directive. This add a event listener for click done outside a component.
import {Directive, ElementRef, HostListener, EventEmitter, Output} from '@angular/core';
@Directive({
selector: '[clickedOutside]'
})
export class ClickedOutsideDirective {
@Output()
public clickedOutside = new EventEmitter();
constructor(private _elemRef: ElementRef) {
}
@HostListener('document:click', ['$event'])
public onClick(event) {
const targetElement = event.target;
if (!targetElement) {
return;
}
/**
* In case the target element which was present inside the referred element
* is removed from the DOM before this method is called, then clickedInside
* will be false even if the clicked element was inside the ref Element. So
* if you don't want this behaviour then use [hidden] instead of *ngIf
*/
const clickedInside = this._elemRef.nativeElement.contains(targetElement);
if (!clickedInside && !this._elemRef.nativeElement.isSameNode(targetElement)) {
return this.clickedOutside.emit(event);
}
}
}
This can be used as follows:
<app-comp (clickedOutside)='close()'></app-comp>
close
will be triggered whenever someone clicks outside app-comp
Upvotes: 3
Reputation: 1632
In Simple Terms
Component Directive will be your directives with template which we use a lot while building a app -> in your html -> <custom-tag></custom-tag>
@Component({
selector : 'custom-tag',
template : '<p> My Custom Tag</p>'
})
Structural Directive are the ones that modify the DOM, by removing adding elements. Example would be
<div *ngIf="showErrorMessage">{{errorMessage}}</div>
ngIf would add the div if true else remove if it changes to false.
Lastly are the Attribute Directive, the name says it all..its a 'attribute based directive' Example would be :
<input type="text" pPassword />
@Directive({
selector: '[pPassword]'
})
Upvotes: 10
Reputation: 129
There are three kinds of Angular directives:
Components
Attribute directives
Structural directives
Angular2 Guide Attribute Directives Code : https://github.com/guyoung/GyPractice-Angular2/tree/master/apps/attribute-directives
Angular2 Guide Structural Directives Code : https://github.com/guyoung/GyPractice-Angular2/tree/master/apps/structural-directives
Upvotes: 5
Reputation: 55443
Simple-Directive-Demo . This is a very simple example to start with angular2 directive.
I have a component and directive.
I use directive to update component's view. Moreover directive's changeColor function is getting called with a component's changeColor function.
Component
@Component({
selector: 'my-app',
host: {'[style.backgroundColor]':'color',}
template: `
<input type="text" [(ngModel)]="color" (blur)="changeColor(color)" />
<br>
<span > (span) I'm {{color}} color <span>
<div mySelectedColor [selectedColor]="color"> (div) I'm {{color}} color </div>
`,
directives: [selectedColorDirective]
})
export class AppComponent implements AfterViewInit{
@ViewChild(selectedColorDirective) myDirective: selectedColorDirective;
color:string;
constructor(el:ElementRef,renderer:Renderer) {
this.color="Yellow";
//renderer.setElementStyle(el, 'backgroundColor', this.color);
}
changeColor(color)
{
this.myDirective.changeColor(this.color);
}
ngAfterViewInit() { }
}
Directive
@Directive({
selector:"[mySelectedColor]",
host: {
// '(keyup)': 'changeColor()',
// '[style.color]': 'selectedColor',
}
})
export class selectedColorDirective {
@Input() selectedColor: string = '';
constructor(el: ElementRef, renderer: Renderer) {
this.el=el;
this.el.nativeElement.style.backgroundColor = 'pink';
// renderer.setElementStyle(el, 'backgroundColor', this.selectedColor);
}
changeColor(clr)
{
console.log('changeColor called ' + clr);
//console.log(this.el.nativeElement);
this.el.nativeElement.style.backgroundColor = clr;
}
}
Upvotes: 18