Angular Interview Questions

34 Questions
Angular

Angular

FrontendWeb Development

Question 9

What are directives in Angular, and how do they work?

Answer:

Directives in Angular are special markers or instructions in the DOM that tell Angular to do something with a DOM element or even an entire DOM tree. They are a fundamental part of Angular's architecture and are used to extend the capabilities of HTML by providing new syntax. Directives can be categorized into three main types: Component Directives, Structural Directives, and Attribute Directives.

1. Component Directives:

  • Definition: Components are a type of directive with a template. They are the most common directive type and define the major building blocks of an Angular application.
  • Purpose: Component directives create custom HTML elements that Angular can manage.
  • Example:
    import { Component } from '@angular/core';
    
    @Component({
      selector: 'app-example',
      template: '<h1>Hello, {{ name }}!</h1>'
    })
    export class ExampleComponent {
      name: string = 'Angular';
    }

2. Structural Directives:

  • Definition: Structural directives change the DOM layout by adding or removing elements. They are applied using the * prefix.
  • Purpose: To conditionally include or repeat elements in the DOM.
  • Common Structural Directives:
    • *ngIf: Adds or removes an element based on a boolean expression.
    • *ngFor: Repeats an element for each item in a collection.
    • *ngSwitch: Switches between alternative views based on a matching expression.
  • Example:
    <div *ngIf="isVisible">This content is visible</div>
    
    <ul>
      <li *ngFor="let item of items">{{ item }}</li>
    </ul>

3. Attribute Directives:

  • Definition: Attribute directives change the appearance or behavior of an element, component, or another directive. They look like regular HTML attributes.
  • Purpose: To modify the behavior or style of elements.
  • Common Attribute Directives:
    • ngClass: Adds and removes a set of CSS classes.
    • ngStyle: Adds and removes a set of inline styles.
    • ngModel: Binds an input, select, or textarea element to a variable (used in two-way data binding).
  • Example:
    <div [ngClass]="{ 'highlight': isHighlighted }">Highlighted content</div>
    <div [ngStyle]="{ 'color': textColor }">Styled content</div>

How Directives Work:

  1. Declaration:

    • Directives are declared in an Angular module in the declarations array.
    • Example:
      import { NgModule } from '@angular/core';
      import { BrowserModule } from '@angular/platform-browser';
      import { AppComponent } from './app.component';
      import { HighlightDirective } from './highlight.directive';
      
      @NgModule({
        declarations: [
          AppComponent,
          HighlightDirective
        ],
        imports: [BrowserModule],
        providers: [],
        bootstrap: [AppComponent]
      })
      export class AppModule { }
  2. Usage:

    • Structural directives use the * syntax to modify the structure of the DOM.
    • Attribute directives use square brackets [] to bind to the properties of DOM elements.
    • Example:
      <div *ngIf="showContent">Content to display conditionally</div>
      <button [disabled]="isDisabled">Click Me</button>
  3. Custom Directives:

    • You can create custom directives to encapsulate specific behaviors.
    • Example of a custom attribute directive:
      import { Directive, ElementRef, Renderer2, HostListener } from '@angular/core';
      
      @Directive({
        selector: '[appHighlight]'
      })
      export class HighlightDirective {
        constructor(private el: ElementRef, private renderer: Renderer2) {}
      
        @HostListener('mouseenter') onMouseEnter() {
          this.renderer.setStyle(this.el.nativeElement, 'backgroundColor', 'yellow');
        }
      
        @HostListener('mouseleave') onMouseLeave() {
          this.renderer.removeStyle(this.el.nativeElement, 'backgroundColor');
        }
      }

In Summary:
Directives in Angular are essential tools for extending HTML functionality and building dynamic, interactive web applications. They come in three main types:

  1. Component Directives: Define reusable components with a template.
  2. Structural Directives: Modify the DOM structure (e.g., *ngIf, *ngFor).
  3. Attribute Directives: Change the appearance or behavior of elements (e.g., ngClass, ngStyle).

These directives work by manipulating the DOM based on the logic defined in your Angular application, providing a powerful way to create rich user experiences.

Recent job openings