About Us
IDKBlogs

  All  
Javascript
NodeJS
AngularJS
Angular2+
ReactJS
Others

Custom directive in Angular 2 application

  idkblogs.com      August 9, 2017

Shubham Verma

Shubham Verma


Custom directive in Angular 2 application

Directives are the unit part of the angular app, In angular app we broadly use the components, actually, component is a directive. They are higher order directive with templates and they are building blocks of angular applications. Here we'll talk about the custom directive. If you want to create custom directory in angular 2+ app then follow the given steps in this article. In this article, we will create a directive and In this directive our goal is to add some HTML content at the desire place. ( The directive will add HTML content in the DOM ).

Create an angular2+ app:

First we need to create an angular app using "ng new" command, create an app using below command:

ng new angular-dir
cd angular-dir
npm install

After successful npm install, we need to create a directive in your app, so go to the folder "src/app" and follow the below steps:

Create a test.directive.ts file.

In this step, we will create a directory and further we will use this directory throughout the app. To do this we need to Create a file name "test.directive.ts" ( src/app/test.directive.ts ) and write the below code in this file.


                          
                      

Now your custom directive has been created .

Now you will have to import this custom directive in app.module.ts.

After creating the directory, you need to add this directive in your module, to do this import and add this directive in your "app.module.ts"

app.module.ts:


                      import { NgModule } from ‘@angular/core’;
                      import { AppComponent } from ‘./app.component’;
                      import { TestDirectives } from ‘../directives/test.directive’;
                      @NgModule({
                         declarations: [
                         AppComponent,
                         TestDirectives
                       ],
                      imports: [],
                      providers: [],
                      bootstrap: [AppComponent]
                      });
                      export class AppModule { }
                    

Now your directive has been imported in your app successfully.

Use your custom directive.

Now you are free to add this custom directive any where within the module like this:

See the output.

In the output you can see the "Hello World" append in your dom just because of your custom directive


Conclusion:

In this article, we tried to describe about the custom directive. Hope you are able to write the custom directive in angular2+ app.


Thank you

for taking the time to read this article. If you’re interested in Node.js or JavaScript this link will help you a lot.



Copyright © 2020 IDKBlogs | All Right Reserved

About Us

Powered by : IDKBlogs

Last Update : 19/09/2020