Introduction
In this article, we will see how the different types of directives work in Angular.
Angular has three types of directives.
- Component
- Structural
- Directives
Component directives have their own template. It is identified by @Component decorator that defines the class defined is component class. We can define a component view with its template. Template tells Angular how to render the component.
Structural directives are used to change the structure of the HTML element. An * is added in the directive attribute name. It is helpful to shape/reshape the DOM’s structure by manipulating the elements. We can use one structural directive for a particular host element.
Attribute Directives are used to change the behavior of the DOM element. It uses @Directive annotation decorated on the class.
Let’s have an example with the use of component, structure, and attribute directive used in Angular.
- Create an Angular project.
- Create a test component.
Ng g c testDirective

- Create a directive.
Ng g c mydir

Open my-dir.directrive.ts and add/modify with the below conent.
- import { Directive, ElementRef } from '@angular/core';
- @Directive({
- selector: '[appMyDir]'
- })
- export class MyDirDirective {
- constructor(el: ElementRef) {
- el.nativeElement.style.background='red';
- el.nativeElement.style.width='200px';
- }
- }
Open test-directive.component.ts and modify with the below content.
- import { Component, OnInit, Input } from '@angular/core';
- @Component({
- selector: 'app-test-directive',
- templateUrl: './test-directive.component.html',
- styleUrls: ['./test-directive.component.css']
- })
- export class TestDirectiveComponent implements OnInit {
- @Input('name') name : string;
- @Input('phone') phone : string;
- constructor() {}
- ngOnInit() {
- }
- }
Open test-directive.component.html and add the below content.
- {{name}} : {{phone}}
- <p appMyDir>This text is under custom directive decorated by @directive</p>
Open app.component.ts and modify with the below code.


Sani YadavPosted Apr 17, 2020, 12:22 PM
Very good article
Mageshwaran RPosted Nov 16, 2019, 9:21 AM
Nice Article sir...