Component Basics

Understanding the basics of Angular components including component class, decorator, and template.

Component Basics Interview with follow-up questions

Question 1: What is a component in Angular?

Answer:

In Angular, a component is a building block of the application that represents a part of the user interface. It encapsulates the HTML template, styles, and behavior logic of a specific part of the application. Components are reusable and can be composed together to create complex user interfaces.

Back to Top ↑

Follow up 1: How do you create a component in Angular?

Answer:

To create a component in Angular, you can use the @Component decorator along with a TypeScript class. The @Component decorator is used to define the metadata for the component, such as the selector, template, styles, and more. Here's an example of creating a component:

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

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

Follow up 2: What are the different parts of an Angular component?

Answer:

An Angular component consists of several parts:

  1. Selector: It is used to define how the component can be used in the HTML template.
  2. Template: It defines the HTML structure of the component.
  3. Styles: It defines the CSS styles for the component.
  4. Class: It is the TypeScript class that contains the component's logic and data.
  5. Metadata: It is defined using the @Component decorator and contains additional information about the component, such as inputs, outputs, and lifecycle hooks.
Back to Top ↑

Follow up 3: Can you explain the lifecycle of an Angular component?

Answer:

The lifecycle of an Angular component consists of several phases:

  1. Creation: The component is created by Angular.
  2. Initialization: The component's properties are initialized.
  3. Change detection: Angular checks for changes in the component's properties and updates the view if necessary.
  4. Content projection: If the component has content projection, the projected content is inserted into the component's template.
  5. Destroy: The component is destroyed and any resources are released.

During each phase, Angular provides lifecycle hooks that allow you to execute custom logic. Some of the commonly used lifecycle hooks are ngOnInit, ngOnChanges, ngDoCheck, ngAfterViewInit, and ngOnDestroy.

Back to Top ↑

Question 2: What is the role of the @Component decorator in Angular?

Answer:

The @Component decorator is used to define and configure an Angular component. It marks a class as an Angular component and provides metadata that determines how the component should be processed, instantiated, and used at runtime.

Back to Top ↑

Follow up 1: What information does the @Component decorator hold?

Answer:

The @Component decorator holds metadata that defines various aspects of an Angular component, including its selector, template or templateUrl, styles or styleUrls, inputs, outputs, and providers. It also allows for the configuration of change detection strategy, view encapsulation, and other component-specific settings.

Back to Top ↑

Follow up 2: How does the @Component decorator relate to the template of an Angular component?

Answer:

The @Component decorator is used to specify the template or templateUrl of an Angular component. The template defines the structure and layout of the component's view, while the templateUrl allows for the use of an external HTML file as the component's template. The @Component decorator also allows for the configuration of inline styles or external style files using the styles or styleUrls properties.

Back to Top ↑

Follow up 3: Can you give an example of the usage of the @Component decorator?

Answer:

Sure! Here's an example of how the @Component decorator can be used:

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

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

Question 3: How do you communicate between components in Angular?

Answer:

In Angular, you can communicate between components using @Input and @Output decorators, EventEmitter, and services.

@Input and @Output decorators allow you to pass data from a parent component to a child component and vice versa. @Input is used to pass data from a parent component to a child component, while @Output is used to emit events from a child component to a parent component.

EventEmitter is a class in Angular that allows you to create custom events and emit them from a component. It can be used to communicate between components that are not directly related, such as sibling components or components at different levels in the component tree.

Services are another way to communicate between components in Angular. Services are singleton objects that can be injected into multiple components and used to share data or functionality between them.

Back to Top ↑

Follow up 1: What is @Input and @Output in Angular?

Answer:

@Input and @Output are decorators in Angular that are used for component communication.

@Input decorator is used to pass data from a parent component to a child component. It allows a parent component to bind a value to a property of a child component. The child component can then access and use this value.

@Output decorator is used to emit events from a child component to a parent component. It allows a child component to define custom events and emit them. The parent component can then listen to these events and respond to them.

Back to Top ↑

Follow up 2: Can you give an example of parent-child communication in Angular?

Answer:

Sure! Here's an example of parent-child communication in Angular using @Input and @Output decorators:

Parent Component:

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

@Component({
  selector: 'app-parent',
  template: `
    <h2>Parent Component</h2>

  `
})
export class ParentComponent {
}

Child Component:

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

@Component({
  selector: 'app-child',
  template: `
    <h4>Child Component</h4>
    <p>{{ message }}</p>
    Send Message to Parent
  `
})
export class ChildComponent {
  @Input() message: string;
  @Output() messageSent: EventEmitter = new EventEmitter();

  sendMessage() {
    this.messageSent.emit('Hello from child');
  }
}

In this example, the parent component passes the message 'Hello from parent' to the child component using the @Input decorator. The child component displays this message and also emits a custom event using the @Output decorator when the 'Send Message to Parent' button is clicked. The parent component listens to this event and can respond to it.

Back to Top ↑

Follow up 3: What is an Event Emitter in Angular?

Answer:

In Angular, an Event Emitter is a class that allows you to create custom events and emit them from a component. It is used for component communication, specifically for emitting events from a child component to a parent component.

To use an Event Emitter, you need to import it from the '@angular/core' module and create an instance of it in your component. You can then define custom events using the Event Emitter and emit them using the 'emit' method.

Here's an example of using an Event Emitter in Angular:

import { Component, EventEmitter, Output } from '@angular/core';

@Component({
  selector: 'app-child',
  template: `
    Send Message
  `
})
export class ChildComponent {
  @Output() messageSent: EventEmitter = new EventEmitter();

  sendMessage() {
    this.messageSent.emit('Hello from child');
  }
}

In this example, the child component defines a custom event called 'messageSent' using the Event Emitter. When the 'Send Message' button is clicked, the child component emits this event with the message 'Hello from child'. The parent component can listen to this event and respond to it.

Back to Top ↑

Question 4: What is the difference between a component and a directive in Angular?

Answer:

In Angular, a component is a building block of an application that controls a part of the user interface (UI) and can be reused throughout the application. It consists of a template, which defines the structure and layout of the UI, and a class, which contains the logic and data for the UI.

On the other hand, a directive is a way to extend the behavior of an existing element or create a new reusable element. Directives are used to manipulate the DOM, add event listeners, apply styles, and perform other low-level operations. Unlike components, directives do not have their own template and are typically used to enhance the functionality of existing elements or create custom elements.

Back to Top ↑

Follow up 1: Can you give an example where a directive would be more appropriate to use than a component?

Answer:

Sure! Let's say you have a form in your application and you want to validate the input fields. Instead of creating a separate component for each input field, you can create a directive that handles the validation logic and apply it to the input elements. This way, you can reuse the validation logic across multiple input fields without duplicating code.

Here's an example of a directive that validates an email input field:

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

@Directive({
  selector: '[appEmailValidator]'
})
export class EmailValidatorDirective {
  constructor(private el: ElementRef) {}

  @HostListener('blur')
  onBlur() {
    const value = this.el.nativeElement.value;
    if (!value.includes('@')) {
      this.el.nativeElement.classList.add('invalid');
    } else {
      this.el.nativeElement.classList.remove('invalid');
    }
  }
}

In this example, the appEmailValidator directive is applied to an input element. When the input field loses focus, the onBlur method is triggered, which checks if the input value contains the '@' symbol. If not, it adds the 'invalid' class to the element.

Back to Top ↑

Follow up 2: How do you create a directive in Angular?

Answer:

To create a directive in Angular, you can use the @Directive decorator. Here are the steps:

  1. Create a new TypeScript file for your directive, e.g., my-directive.directive.ts.
  2. Import the necessary dependencies from @angular/core, such as Directive, ElementRef, HostListener, etc.
  3. Decorate your directive class with the @Directive decorator, specifying the selector for your directive.
  4. Implement the logic for your directive inside the class.

Here's an example of a basic directive that changes the background color of an element when clicked:

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

@Directive({
  selector: '[appHighlight]'
})
export class HighlightDirective {
  constructor(private el: ElementRef) {}

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

In this example, the appHighlight directive is applied to an element. When the element is clicked, the onClick method is triggered, which changes the background color of the element to yellow.

Back to Top ↑

Follow up 3: What are the different types of directives in Angular?

Answer:

In Angular, there are three types of directives:

  1. Component Directives: These are the most common type of directives in Angular. They are used to create reusable UI components with their own template and logic. Components are declared using the @Component decorator.

  2. Attribute Directives: These directives are used to modify the behavior or appearance of an existing element. They are applied using an attribute on the element. Attribute directives are declared using the @Directive decorator.

  3. Structural Directives: These directives are used to manipulate the structure of the DOM by adding, removing, or manipulating elements. They are applied using a special syntax in the template. Structural directives are declared using the @Directive decorator with a * prefix.

Examples of built-in structural directives in Angular are ngIf, ngFor, and ngSwitch.

Back to Top ↑

Question 5: How do you handle data in an Angular component?

Answer:

In Angular, data in a component can be handled using data binding. Data binding is a mechanism that allows you to synchronize data between the component and the template. There are three types of data binding in Angular: one-way binding, two-way binding, and event binding.

Back to Top ↑

Follow up 1: What is the difference between one-way and two-way data binding?

Answer:

One-way data binding in Angular is a unidirectional flow of data from the component to the template. It means that changes in the component will be reflected in the template, but changes in the template will not affect the component.

Two-way data binding in Angular is a bidirectional flow of data between the component and the template. It means that changes in the component will be reflected in the template, and changes in the template will also affect the component.

Back to Top ↑

Follow up 2: How do you implement two-way data binding in Angular?

Answer:

In Angular, two-way data binding can be implemented using the ngModel directive. The ngModel directive is used to bind the value of an input element to a property in the component. It allows you to both read and write the value of the input element.

Here is an example of how to implement two-way data binding in Angular:


In the above example, the value of the input element is bound to the 'name' property in the component. Any changes in the input element will update the 'name' property, and any changes in the 'name' property will update the input element.

Back to Top ↑

Follow up 3: What is data binding in Angular?

Answer:

Data binding in Angular is a mechanism that allows you to synchronize data between the component and the template. It enables you to update the view whenever the data changes, and update the data whenever the user interacts with the view. There are three types of data binding in Angular: one-way binding, two-way binding, and event binding.

Back to Top ↑