Components vs Directives

Understanding the difference between components and directives in Angular.

Components vs Directives Interview with follow-up questions

Interview Question Index

Question 1: What is the main difference between components and directives in Angular?

Answer:

Components are a type of directive that have a template and are used to create reusable UI elements. Directives, on the other hand, are used to manipulate the behavior or appearance of existing elements in the DOM.

Back to Top ↑

Follow up 1: Can you give an example of when you would use a component over a directive?

Answer:

Components are typically used when you want to create a reusable UI element that encapsulates its own behavior and template. For example, if you want to create a custom button with specific styling and functionality, you would create a component. Directives, on the other hand, are used when you want to manipulate the behavior or appearance of existing elements in the DOM without creating a separate UI element.

Back to Top ↑

Follow up 2: What are some of the common directives used in Angular?

Answer:

Some of the common directives used in Angular are:

  • ngIf: Used to conditionally show or hide elements based on a condition.
  • ngFor: Used to iterate over a collection and render elements for each item.
  • ngClass: Used to add or remove CSS classes based on a condition.
  • ngStyle: Used to dynamically apply inline styles to elements.
  • ngModel: Used for two-way data binding between a form control and a component.
  • ngSubmit: Used to handle form submission events.
  • ngSwitch: Used to conditionally render elements based on a specific value.
Back to Top ↑

Follow up 3: How do you define a custom directive in Angular?

Answer:

To define a custom directive in Angular, you can use the @Directive decorator. Here's an example:

import { Directive, ElementRef } from '@angular/core';

@Directive({
  selector: '[appCustomDirective]'
})
export class CustomDirective {
  constructor(private elementRef: ElementRef) {
    this.elementRef.nativeElement.style.backgroundColor = 'red';
  }
}

In this example, the custom directive is applied to elements with the attribute 'appCustomDirective'. The directive's constructor injects the ElementRef, which gives access to the DOM element that the directive is applied to. In this case, the directive sets the background color of the element to red.

Back to Top ↑

Question 2: How can you identify whether a particular element in Angular is a component or a directive?

Answer:

To identify whether a particular element in Angular is a component or a directive, you can look at the element's HTML tag. Components in Angular are typically represented by custom HTML tags, while directives are represented by attributes on existing HTML tags. If the element has a custom HTML tag, it is most likely a component. If it has an attribute, it is most likely a directive.

Back to Top ↑

Follow up 1: What are the key parts of a component?

Answer:

The key parts of a component in Angular are:

  1. Template: The HTML markup that defines the component's view.
  2. Class: The TypeScript class that contains the component's logic and data.
  3. Metadata: The decorator that provides Angular with information about the component, such as its selector, template, and styles.
Back to Top ↑

Follow up 2: What are the key parts of a directive?

Answer:

The key parts of a directive in Angular are:

  1. Selector: The attribute or element that triggers the directive.
  2. Host: The element that the directive is attached to.
  3. Template: The HTML markup that defines the directive's behavior.
  4. Class: The TypeScript class that contains the directive's logic and data.
  5. Metadata: The decorator that provides Angular with information about the directive, such as its selector and template.
Back to Top ↑

Follow up 3: Can a component be used as a directive?

Answer:

Yes, a component can be used as a directive in Angular. Components are a type of directive that have their own view, while other types of directives typically modify the behavior or appearance of existing elements. By using a component as a directive, you can reuse the component's logic and data without rendering its view.

Back to Top ↑

Question 3: Can you explain the lifecycle of a component and a directive in Angular?

Answer:

In Angular, both components and directives have a lifecycle that consists of several phases. The lifecycle of a component or directive starts when it is created and ends when it is destroyed. During this lifecycle, Angular provides several lifecycle hooks that allow you to tap into different stages of the component or directive's lifecycle and perform certain actions.

The lifecycle of a component or directive can be divided into the following phases:

  1. Creation: This phase starts when the component or directive is instantiated. During this phase, Angular sets up the component or directive and initializes its properties.

  2. Change detection: This phase is triggered whenever there is a change in the component or directive's input properties or when an event is emitted. Angular checks for changes and updates the component or directive's view accordingly.

  3. Content projection: This phase is specific to components and is triggered when the component's content is projected into its template.

  4. Destruction: This phase occurs when the component or directive is about to be destroyed. During this phase, Angular cleans up any resources associated with the component or directive.

It's important to note that the lifecycle of a component and a directive is not exactly the same. Components have a more complex lifecycle compared to directives, as they have additional phases like view initialization and view destruction.

Back to Top ↑

Follow up 1: What are the different lifecycle hooks available for a component?

Answer:

In Angular, there are several lifecycle hooks available for a component. These hooks allow you to tap into different stages of the component's lifecycle and perform certain actions. The different lifecycle hooks available for a component are as follows:

  1. ngOnChanges: This hook is called whenever there is a change in the component's input properties. It receives a SimpleChanges object that contains the previous and current values of the input properties.

  2. ngOnInit: This hook is called after the component's constructor and ngOnChanges hook have been called for the first time. It is used for initialization tasks such as retrieving data from a server.

  3. ngDoCheck: This hook is called during every change detection cycle. It is used to detect and act upon changes that Angular cannot detect automatically.

  4. ngAfterContentInit: This hook is called after Angular projects external content into the component's view.

  5. ngAfterContentChecked: This hook is called after Angular checks the content projected into the component's view.

  6. ngAfterViewInit: This hook is called after Angular initializes the component's view and child views.

  7. ngAfterViewChecked: This hook is called after Angular checks the component's view and child views.

  8. ngOnDestroy: This hook is called just before the component is destroyed. It is used for cleanup tasks such as unsubscribing from observables and releasing resources.

Back to Top ↑

Follow up 2: What are the different lifecycle hooks available for a directive?

Answer:

In Angular, there are several lifecycle hooks available for a directive. These hooks allow you to tap into different stages of the directive's lifecycle and perform certain actions. The different lifecycle hooks available for a directive are as follows:

  1. ngOnChanges: This hook is called whenever there is a change in the directive's input properties. It receives a SimpleChanges object that contains the previous and current values of the input properties.

  2. ngOnInit: This hook is called after the directive's constructor and ngOnChanges hook have been called for the first time. It is used for initialization tasks such as retrieving data from a server.

  3. ngDoCheck: This hook is called during every change detection cycle. It is used to detect and act upon changes that Angular cannot detect automatically.

  4. ngOnDestroy: This hook is called just before the directive is destroyed. It is used for cleanup tasks such as unsubscribing from observables and releasing resources.

Back to Top ↑

Follow up 3: Can you give an example of how you would use a lifecycle hook in a component or directive?

Answer:

Sure! Let's take the example of the ngOnChanges hook, which is called whenever there is a change in the component or directive's input properties. Suppose we have a component that takes an input property called 'name'. We can use the ngOnChanges hook to perform some action whenever the 'name' input property changes. Here's an example:

import { Component, Input, OnChanges, SimpleChanges } from '@angular/core';

@Component({
  selector: 'app-example',
  template: `<p>Hello, {{ name }}!</p>`
})
export class ExampleComponent implements OnChanges {
  @Input() name: string;

  ngOnChanges(changes: SimpleChanges) {
    if (changes.name) {
      console.log('The name input property has changed.');
      console.log('Previous value:', changes.name.previousValue);
      console.log('Current value:', changes.name.currentValue);
    }
  }
}

In this example, whenever the 'name' input property changes, the ngOnChanges hook is called and we log the previous and current values of the 'name' input property.

This is just one example, and there are many other ways to use lifecycle hooks in components and directives depending on your specific use case.

Back to Top ↑

Question 4: What is the purpose of the @Component and @Directive decorators in Angular?

Answer:

The @Component and @Directive decorators in Angular are used to create reusable UI components and to extend the behavior of existing elements respectively.

The @Component decorator is used to define a new component in Angular. It provides metadata about the component, such as its selector, template, styles, and more. This metadata is used by Angular to instantiate and render the component.

The @Directive decorator, on the other hand, is used to define a new directive in Angular. Directives are used to modify the behavior or appearance of existing elements. They can be used to add event listeners, manipulate the DOM, or apply custom styles.

Back to Top ↑

Follow up 1: What information do you provide to the @Component decorator?

Answer:

The @Component decorator accepts an object as an argument, which contains various properties to configure the component. Some of the commonly used properties are:

  • selector: Specifies the CSS selector that identifies the component in a template.
  • template/templateUrl: Specifies the HTML template for the component.
  • styles/styleUrls: Specifies the CSS styles for the component.
  • providers: Specifies the services that the component requires.

Here is an example of how you would use the @Component decorator:

import { Component } from '@angular/core';

@Component({
  selector: 'app-example',
  template: '<h1>Hello, World!</h1>',
  styles: ['h1 { color: red; }']
})
export class ExampleComponent {
  // Component logic goes here
}
Back to Top ↑

Follow up 2: What information do you provide to the @Directive decorator?

Answer:

The @Directive decorator accepts an object as an argument, which contains various properties to configure the directive. Some of the commonly used properties are:

  • selector: Specifies the CSS selector that identifies the elements to which the directive should be applied.
  • inputs/outputs: Specifies the input and output properties of the directive.
  • host: Specifies the event listeners and host properties of the directive.

Here is an example of how you would use the @Directive decorator:

import { Directive, ElementRef, HostListener } from '@angular/core';

@Directive({
  selector: '[appExample]'
})
export class ExampleDirective {
  constructor(private elementRef: ElementRef) {}

  @HostListener('click')
  onClick() {
    this.elementRef.nativeElement.style.backgroundColor = 'red';
  }
}
Back to Top ↑

Follow up 3: Can you give an example of how you would use the @Component and @Directive decorators?

Answer:

Sure! Here is an example of how you would use both the @Component and @Directive decorators:

import { Component, Directive, ElementRef, HostListener } from '@angular/core';

@Directive({
  selector: '[appExample]'
})
export class ExampleDirective {
  constructor(private elementRef: ElementRef) {}

  @HostListener('click')
  onClick() {
    this.elementRef.nativeElement.style.backgroundColor = 'red';
  }
}

@Component({
  selector: 'app-example',
  template: '<h1>Hello, World!</h1>',
  styles: ['h1 { color: blue; }']
})
export class ExampleComponent {
  // Component logic goes here
}
Back to Top ↑

Question 5: How do you handle events in components and directives?

Answer:

In Angular, events can be handled using event binding. Event binding allows you to listen to and respond to events such as button clicks, mouse movements, and keyboard inputs. You can bind event handlers to HTML elements or Angular directives using the (event) syntax.

Back to Top ↑

Follow up 1: What is event binding in Angular?

Answer:

Event binding in Angular is a way to handle events raised by HTML elements or Angular directives. It allows you to listen to events such as button clicks, mouse movements, and keyboard inputs, and execute a function or perform some action in response to those events. Event binding is denoted by the (event) syntax in Angular templates.

Back to Top ↑

Follow up 2: How do you bind to user input events like clicks and key presses?

Answer:

To bind to user input events like clicks and key presses, you can use event binding in Angular. For example, to bind to a button click event, you can use the (click) event binding syntax. Similarly, to bind to a key press event, you can use the (keyup) or (keydown) event binding syntax. Inside the event binding expression, you can call a method or execute any JavaScript code to handle the event.

Back to Top ↑

Follow up 3: Can you give an example of how you would use event binding in a component or directive?

Answer:

Sure! Here's an example of how you can use event binding in an Angular component:

Click me

In this example, the (click) event binding is used to bind the handleButtonClick() method to the button's click event. When the button is clicked, the handleButtonClick() method will be executed. You can define the handleButtonClick() method in the component's TypeScript code to perform any desired action.

Back to Top ↑