Custom Directive
- You can create custom directives to have more control over behavior of DOM elements
- You can create directive from scratch or use cli to generate it
Create Directive using Angular CLI
ng g d input-format
- You have to register directives, components, pipes in the module that are part of it.
- The selector has [] brackets, angular finds the element that has this attributes it is going to apply the directive on that element
- HostListener is a decorator function that allows us to subscribe to the events raised from the DOM elements that is hosting this directive or element that has the attribute
- Import HostListener
import {HostListener} from "@angular/core";
- Inject ElementRef in the constructor, the service defined in angular that give us access to DOM object
- Nativeelement give access to the actual dom object
constructor(private el: ElementRef)
- Use HostListener to specify the event name to subscribe
@HostListener('focus') onFocus(){
console.log("on focus");
}
@HostListener('blur') onBlur() {
let value: string = this.el.nativeElement.value;
this.el.nativeElement.value = value.toLowercase();
console.log(value)
}
<input appInputElement>
- You can pass data to directives using input properties
- If you have only 1 property we can use the selector of that directive as an alias for that property and simplies the usage of custom directive
@Input('format') format;
<input appInputElement [format]="'uppercase'">
- If only 1 value to pass to directive
@Input('appInputElement') format;
<input [appInputElement]="'uppercase'">