This post lists some subjective questions and answers related to Directives in Angular. This collection contains some potential interview questions that may be helpful if you are preparing for a Frontend Engineering job interview specific to Angular framework. Check out Angular Interview Series – Topic Wise Q&A.
1. What is a directive in Angular?
A directive is a class that adds behavior to elements in Angular applications, allowing you to manipulate the DOM or modify the appearance and behavior of components.
2. What are different types of directives in Angular?
There are three types of directives in Angular. They are as follows:
- Component Directives: Directives with a template; they are the most common type.
- Structural Directives: Change the DOM layout by adding or removing elements (e.g.,
*ngIf,*ngFor). - Attribute Directives: Change the appearance or behavior of an element (e.g.,
ngClass,ngStyle).
3. What is a structural directive?
A structural directive modifies the structure of the DOM by adding or removing elements based on certain conditions, using an asterisk (*) prefix (e.g., *ngIf, *ngFor).
4. How do you create a custom directive in Angular?
We create a custom directive using the Angular CLI with the command:
ng generate directive directive-nameand then implement the desired behavior in the directive class.
5. What is the purpose of the @Directive() decorator?
The @Directive() decorator is used to define a directive and provide metadata, such as the selector that identifies the directive in templates.
6. How can you pass parameters to an attribute directive?
We can pass parameters to an attribute directive using square brackets in the template, e.g., <div appMyDirective [param]="value"></div>.
7. What is the difference between an attribute directive and a structural directive?
An attribute directive modifies the appearance or behavior of an existing element, while a structural directive modifies the DOM structure by adding or removing elements.
8. What is ngClass used for?
ngClass is an attribute directive that dynamically adds or removes CSS classes to an element based on a specified condition or expression.
9. What is ngStyle used for?
ngStyle is an attribute directive that dynamically applies inline styles to an element based on a specified condition or expression.
10. Can you apply multiple directives to a single element?
Yes, We can apply multiple directives to a single element, and they will work together to modify the element’s behavior and appearance.
These are a few questionnaires specific to Angular directives. I will be adding more questions and answers to this post. To know more details please refer to the Official documentation on Angular Directives.
