Creating and using an attribute directive in Angular 13

Tram Ho

In this article, I will share the creation and use of 2 attribute directives named appLink and appCapitalize in angular 13.
Directive appLink : has the task of displaying the corresponding background color of each card and checking if the value in the tag is a link, if it is valid, open the link to a new tab, if it is not, alert an error message.
Directive appCapitalize : is responsible for automatically capitalizing the first letter of each word when the user enters text from input or textarea.

  1. Create directive appLink

Run the command below to create the appLink directive

After just running the above command, CLI will create 2 files src/app/link/link.directive.ts and src/app/link/link.directive.spec.ts and declare class LinkDirective in AppModule .
The default src/app/link/link.directive.ts code is as follows:

Continue, update the logic code to src /app/link/link.directive.ts as below:

  • ElementRef grants direct access to the DOM element through its nativeElement property.
  • Add ElementRef in constructor() to refer to DOM element, which you apply in appLink .

Next update the code in src/app/app.component.html
Directive appLink is passed to the respective tags with and without the corresponding color parameter.

Ouput :

Now please move your mouse and click on each card to see the results

2.Create directive appCapitalize

  • Run the following command to create the appCapitalize directive:

After just running the above comman, CLI will create 2 files src/app/capitalize/capitalize.directive.ts and src/app/capitalize/capitalize.directive.spec.ts and declare class CapitalizeDirective in AppModule .
The default src/app/capitalize/capitalize.directive.ts code is as follows:

Continue, update the logic code to src/app/capitalize/capitalize.directive.ts as below:

Next update the code in src/app/app.component.html

Ouput :
As you can see, the first word of each word in the input will automatically capitalize when we enter the value in the input or textarea in!

 

Share the news now

Source : Viblo