Questions
What is the difference between a module and a component in Angular?
The Scenario
You are a frontend engineer at a social media company. You are building a new feature that will be used in multiple places in the application.
You are not sure whether to create a new module or a new component.
The Challenge
Explain the difference between a module and a component in Angular. What are the pros and cons of each approach, and which one would you choose for this use case?
A junior engineer might think that they are interchangeable. They might not be aware of the difference in purpose or the design implications of choosing one over the other.
A senior engineer would be able to provide a detailed explanation of the differences between a module and a component. They would also be able to explain the trade-offs between each approach and would have a clear recommendation for which one to use in this use case.
Step 1: Understand the Key Differences
| Feature | Component | Module |
|---|---|---|
| Purpose | To create a new UI element with its own template and logic. | To group related components, directives, pipes, and services together. |
| Template | Has a template. | Does not have a template. |
| Syntax | @Component | @NgModule |
| Use Cases | When you need to create a new UI element. | When you need to organize your application into logical blocks of functionality. |
Step 2: Choose the Right Tool for the Job
For our use case, we should create a new module that contains the new component. This will allow us to easily reuse the component in multiple places in the application.
Step 3: Code Examples
Here’s how we can create a new module and a new component:
my-feature.module.ts:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { MyFeatureComponent } from './my-feature.component';
@NgModule({
imports: [
CommonModule
],
declarations: [
MyFeatureComponent
],
exports: [
MyFeatureComponent
]
})
export class MyFeatureModule { }my-feature.component.ts:
import { Component } from '@angular/core';
@Component({
selector: 'my-feature',
template: '<h1>My Feature</h1>'
})
export class MyFeatureComponent {} Practice Question
You are building a new application and you want to organize your code into logical blocks of functionality. Which of the following would you use?