In this session, I will show you how we can change appearances such as text color, background color and font size of a body of an HTML element using custom attribute directive.
We can create custom attribute directives and custom structural directives using a @Directive decorator. Using custom attribute directive we can change appearances such as text color, background color and font size of a body of an HTML element that can be called the host element. To change appearance Angular provides ElementRef class that can directly access DOM. It is vulnerable to XSS attacks when we directly use ElementRef in our application. It is better to create a custom directive and use ElementRef inside the directive to change the appearance or behavior of the host element.
- Create a class decorated with @Directive.
- Assign the attribute directive name to the selector metadata of @Directive decorator.
- Use ElementRef class to access DOM to change host element appearance and behavior.
- Use @Input() decorator to accept user input in our custom directive.
- Use @HostListener() decorator to listen to events in custom attribute directive.
- Configure custom attribute directive class in the application module in the declarations metadata of @NgModule.
Note
I already have shown you how to create a custom attribute directive and its related files in my previous article. Now instead of repeat previous steps, I will describe only the major points. So, I suggest you before going through this visit my article link as mentioned above.
Custom attribute directives - Dynamic Color
Here we will create an attribute directive named as dynamic color. It will accept two inputs for background color. Second input color will be default color and will be active in the first input if the color has not been given. Now see the code.
Code ref. of dynamic-color.directive.ts
- import { Directive, ElementRef, HostListener, Input } from '@angular/core';
-
- @Directive({
- selector: '[dynamicColor]'
- })
- export class DynamicColorDirective {
- @Input('dynamicColor') dynamicColor: string;
- @Input() defaultValue: string;
- constructor(private elRef: ElementRef) {
- }
- @HostListener('mouseover') onMouseOver() {
- this.changeBackgroundColor(this.dynamicColor || this.defaultValue);
- }
- @HostListener('mouseleave') onMouseLeave() {
- this.changeBackgroundColor('white');
- }
- private changeBackgroundColor(color: string) {
- this.elRef.nativeElement.style.backgroundColor = color;
- }
- }
Code Description
We will create an attribute directive that will accept user input as well listen to events. The role of @Input() decorator is to accept user input and the role of @HostListener() decorator is to listen to the event. Here we will create an attribute directive named as dynamic color. It will accept two inputs for background color. Second input color will be default color and will be active in the first input if the color has not been given.
Code Ref. Of app.component.html
- <div>
- <select [(ngModel)] ="myColor">
- <option value='' selected> Select Color </option>
- <option *ngFor = "let color of colors" [value] = "color">
- {{color}}
- </option>
- </select>
- <p [dynamicColor]="myColor" defaultValue="red"> dynamicColor Directive Demo</p>
- </div>
Code Description
The background color of the text of the host element can be selected from a select box and when the mouse event mouseover is fired, the background color will be displayed as selected in the select box. When the mouse leaves event is fired, a fixed color white will be displayed.
In the above code, colors and myColor are the properties defined in our component, that is app.component.ts
- import { Component } from '@angular/core';
-
- @Component({
- selector: 'Satya-App',
- templateUrl: './app.component.html'
- })
- export class AppComponent {
- txtsize = '25px';
- colors = ['CYAN', 'GREEN', 'YELLOW'];
- myColor = '';
- }
When we select no color, the color assigned to defaultValue will be active and when we select any color from the select box then that color will be active.
OUTPUT
The background color will be displayed as selected in the selected color dropdown when the mouse event mouseover is fired.
When we select no color, the color assigned to defaultValue will be active.
Custom attribute directives - Mouseover and mouseleave events
Code ref. of mouse.directive.ts,
- import { Directive, ElementRef, HostListener } from '@angular/core';
-
- @Directive({
- selector: '[mouseAction]'
- })
- export class MouseActionDirective {
- constructor(private elRef: ElementRef) {
- }
- @HostListener('mouseover') onMouseOver() {
- this.changeBackgroundColor('orange');
- }
- @HostListener('mouseleave') onMouseLeave() {
- this.changeBackgroundColor('green');
- }
- private changeBackgroundColor(color: string) {
- this.elRef.nativeElement.style.backgroundColor = color;
- }
- }
Code Description
We can create custom attribute directive that will perform changes in appearance in DOM when an event is fired. To listen to any event we need to use @HostListener(), decorator. We need to assign event name to @HostListener() decorator. Here we will create an attribute directive that will change the background color of host element when mouseover and mouseleave events are fired.
Code Ref. of app.component.html
- <p mouseAction> mouseAction Directive Demo</p>
Code Description
Here I have mentioned directive name mouseAction.
OUTPUT
On mouseover event.
On mouseleave event.
Custom attribute directives - Customize theme property and default theme property
Code ref. of custom-theme.directive.ts,
- import { Directive, ElementRef, Input, AfterViewInit } from '@angular/core';
-
- @Directive({
- selector: '[customTheme]'
- })
- export class CustomThemeDirective implements AfterViewInit {
- @Input() tcolor: string;
- @Input() bcolor: string;
- @Input() tsize: string;
- constructor(private elRef: ElementRef) {
- }
- ngAfterViewInit(): void {
- this.tcolor = this.tcolor || 'white';
- this.bcolor = this.bcolor || 'orange';
- this.tsize = this.tsize || '20px';
- this.elRef.nativeElement.style.color = this.tcolor;
- this.elRef.nativeElement.style.backgroundColor = this.bcolor;
- this.elRef.nativeElement.style.fontSize = this.tsize;
- }
- }
Code Description
Here we will create an attribute directive that will accept more than one user input. To accept more than one user input, we need to use more than one @Input() decorated property in our class.
Code ref. of app.component.html
- <div customTheme> customTheme Directive Demo with Default Settings</div>
- <div customTheme tcolor="yellow" bcolor="black" tsize="30px"> customTheme Directive Demo with Custom Settings</div>
Code Description
Here I have used a custom theme directive as follows. In the first one, the theme property can be customized using default settings and in the second one, theme property can be customized using custom user input settings.
OUTPUT
Here you can see both setting implementations in theme property.
SUMMARY
- The concept behind custom attribute directive
- Attribute Directive using @Input() and @HostListener() for dynamic color.
- Attribute Directive using @HostListener() to listen to Event for mouseover and mouseleave events
- Attribute Directive using Multiple @Input() for customize theme property and default theme property.