Skip to content

Instantly share code, notes, and snippets.

@d4rkc0de
Created March 21, 2017 11:24
Show Gist options
  • Save d4rkc0de/ddb53a9b29d057348844acc785654cc9 to your computer and use it in GitHub Desktop.
Save d4rkc0de/ddb53a9b29d057348844acc785654cc9 to your computer and use it in GitHub Desktop.
// create new directive with cli :
ng g d directive-name
// directives are used as attribute to existant html element ex :
<div direcrive-name> ... </div>
// example of a directive :
@Directive({
selector: '[myDirectives]'
})
export class Udemy45DirectivesDirective {
constructor(private elementRef:ElementRef,private rederer:Renderer) { // ElementRef,Renderer : need to be imported
this.rederer.setElementStyle(this.elementRef.nativeElement,'background-color','green');
}
}
// inside html :
<div myDirectives><p>Some text</p></div>
// usefull attributes :
@HostListener('event') action() { ... } // listener that can trigger an action() when event. event example : 'mouseenter'.
// ex : @HostListener('mouseenter') mouseenter() { console.log("mouse enterd!!!") }
@HostBinding('property') get setAction() { ... } // host property binding. Angular automatically checks host property bindings during change detection. If a binding changes, it will update the host element of the directive.
// ex : @HostBinding('style.backgroundColor') get setColor() { return this.backgroundColor; }
// cocnlusion : in short term when the HostListener is trigerred it will do the action 'action()', after that what's inside the HostBinding will be called 'setColor()'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment