0
0
Angularframework~5 mins

Importing dependencies directly in Angular

Choose your learning style9 modes available
Introduction

Importing dependencies directly lets you use code from other files or libraries in your Angular component or service. It helps keep your code organized and reusable.

When you want to use Angular built-in features like Component or Injectable decorators.
When you need to use a service or utility function from another file in your project.
When you want to include third-party libraries like RxJS or Angular Material components.
When you want to share code between different parts of your app without copying it.
When you want to keep your code clean and easy to understand by clearly showing where things come from.
Syntax
Angular
import { DependencyName } from 'package-or-file-path';
Use curly braces { } to import specific parts from a package or file.
The path can be a package name (for libraries) or a relative path (for your own files).
Examples
Import the Component decorator from Angular core to create a component.
Angular
import { Component } from '@angular/core';
Import HttpClient to make HTTP requests in your service or component.
Angular
import { HttpClient } from '@angular/common/http';
Import a custom service from a local file using a relative path.
Angular
import { MyService } from './services/my-service.service';
Import the map operator from RxJS to transform observable data.
Angular
import { map } from 'rxjs/operators';
Sample Program

This example shows how to import Angular's Component decorator and CommonModule directly. The component displays a simple heading.

Angular
import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';

@Component({
  selector: 'app-hello',
  standalone: true,
  imports: [CommonModule],
  template: `<h1>Hello, Angular!</h1>`
})
export class HelloComponent {}
OutputSuccess
Important Notes

Always import only what you need to keep your bundle size small.

Use relative paths (starting with ./ or ../) for your own files.

Angular 14+ supports standalone components, so you can import CommonModule directly in the component.

Summary

Importing dependencies directly helps you use code from other files or libraries.

Use curly braces to import specific parts and specify the correct path.

Keep your imports organized to make your code easy to read and maintain.