What is angular directive?
Basically, directives are used to extend the power of the HTML attributes and to change the appearance or behavior of the DOM structure.
It is a TypeScript class which is declared as a @directive decorator. The directives allow you to attach behavior to DOM elements and the @directive decorator provides additional metadata that determine how directives are to be processed, instantiated, and used at run-time.
How many types of directives are supported by Angular?
Angular supports three types of directives
The 3 types of Directives in Angular are:
1. Component Directive
2. Attribute Directive
3. Structural Directive
Components – The component is a directive with its own templates and is responsible for how a component must be processed, instantiated and used at runtime.
Structural Directives – The structural directive is a directive which is responsible for the modification in DOM layout by adding, removing, and manipulating elements. The most of the common built-in structural directives are NgIf, NgFor, and NgSwitch.
Attribute Directives – The Attribute directive is a directive which is responsible for change in the behavior of a particular element or component.
Component directive is a type of directive that always come has a template (view) and is present in an Angular application. To create a component directive, we use the @Component ( ) decorator function
Now, to use this directive, you should code as shown above
This is what we said, directive with template.
The Structural directive modifies the DOM structure by adding or removing DOM elements. Basically, you can say that it works on DOM. These directives always use * as a prefix.
Name some structural directives provided by Angular
Attribute directives are used as element attributes, mainly it change the appearance or behavior of an element, component or directive. By default, Angular provides 2 attribute
directives. They are: –
NgClass : Using NgClass we can add or remove CSS class dynamically, that is, based on certain conditions.
NgStyle: Using NgStyle we can add or remove styles dynamically, that is, based on certain conditions. Example of ngClass and ngStyle is shown below
What is the difference between attribute directive and component directive?
Attribute Directives add behavior to an existing DOM element or to an existing component instance. They help us create reusable component. The @Directive decorator function is used to create an attribute or structural directive.
Instead of adding or changing behavior, a component actually creates its own view (hierarchy of DOM elements) with attached behavior. It helps us to divide an Angular application into smaller components. The @Component decorator function is used to create component directives