Angular JS basics

 

Introduction to Angular

Angular is a platform and framework for building single-page client applications using HTML and TypeScript. It is developed and maintained by Google and offers a robust set of tools to help build complex applications.

Key Concepts

  • Components: Building blocks of Angular applications. Each component consists of an HTML template and a TypeScript class to control its behavior.
  • Modules: Containers for different parts of your app. They help organize an application into cohesive blocks of functionality.
  • Templates: HTML views that define how a component is displayed.
  • Directives: Special syntax to extend HTML with new behaviors.
  • Services: Classes that encapsulate business logic and data. They are often shared across components.
  • Dependency Injection: A design pattern used to inject dependencies (such as services) into components.
  • Routing: Manages navigation between different views or pages in an Angular application.

Setting Up the Development Environment

To start with Angular, you'll need to set up your development environment:

  1. Node.js and npm: Angular CLI is built on top of Node.js. Download and install Node.js which comes with npm (Node Package Manager).

  2. Angular CLI: The Angular Command Line Interface (CLI) helps automate various tasks like creating new projects, components, services, and more.

    Install Angular CLI globally using npm:

    bash
    npm install -g @angular/cli
  3. IDE/Editor: Use an IDE like Visual Studio Code, WebStorm, or any text editor you're comfortable with.

Creating Your First Angular Application

Let's create a simple Angular application using the Angular CLI.

  1. Create a New Angular Project

    Open your terminal or command prompt and run:

    bash
    ng new my-angular-app

    This command creates a new Angular project named my-angular-app. It will prompt you to select a few options like adding Angular routing and the stylesheet format (CSS, SCSS, etc.).

  2. Serve the Application

    Navigate into your project directory and start the development server:

    bash
    cd my-angular-app ng serve

    By default, the application will run at http://localhost:4200/. Open this URL in your browser to see the default Angular application running.

Understanding the Project Structure

When you create a new Angular project, you'll see a structure like this:

java
my-angular-app/ ├── e2e/ ├── node_modules/ ├── src/ │ ├── app/ │ │ ├── app-routing.module.ts │ │ ├── app.component.css │ │ ├── app.component.html │ │ ├── app.component.ts │ │ └── app.module.ts │ ├── assets/ │ ├── environments/ │ ├── favicon.ico │ ├── index.html │ ├── main.ts │ ├── polyfills.ts │ ├── styles.css │ └── test.ts ├── angular.json ├── package.json ├── tsconfig.json └── tslint.json
  • src/app: Contains the main application module and component.
    • app.module.ts: The root module that bootstraps the application.
    • app.component.ts: The root component of the application.
    • app.component.html: The HTML template for the root component.
    • app.component.css: The styles for the root component.
    • app-routing.module.ts: Defines the routing for the application.
  • angular.json: Configuration file for Angular CLI.
  • package.json: Contains information about the project and dependencies.
  • tsconfig.json: TypeScript configuration file.

Building a Simple Component

Now, let’s create a simple component to understand the basic structure and how components work in Angular.

  1. Generate a New Component

    Use Angular CLI to generate a new component:

    bash
    ng generate component hello-world

    This command creates a new folder named hello-world inside the app directory with the following files:

    • hello-world.component.ts: The TypeScript class for the component.
    • hello-world.component.html: The HTML template.
    • hello-world.component.css: The styles.
    • hello-world.component.spec.ts: The test file for the component.
  2. Understanding the Component Files

    hello-world.component.ts

    typescript
    import { Component } from '@angular/core'; @Component({ selector: 'app-hello-world', templateUrl: './hello-world.component.html', styleUrls: ['./hello-world.component.css'] }) export class HelloWorldComponent { message: string = 'Hello, Angular!'; constructor() {} }
    • @Component: A decorator that marks a class as an Angular component and provides metadata, such as the selector, template URL, and styles URL.
    • selector: The HTML tag used to render this component.
    • templateUrl: The HTML template for the component.
    • styleUrls: An array of style files for the component.
    • message: A class property that holds data to be displayed in the template.

    hello-world.component.html

    html
    <h1>{{ message }}</h1>
    • {{ message }}: Angular’s interpolation syntax to bind the component’s property to the template.
  3. Using the Component

    To use the HelloWorldComponent, add its selector <app-hello-world> to the app.component.html file:

    app.component.html

    html
    <h1>Welcome to My Angular App!</h1> <app-hello-world></app-hello-world>
  4. View the Result

    Save all your changes, and you should see the message "Hello, Angular!" displayed on the page when you visit http://localhost:4200/.

Understanding Angular Modules

Modules are a crucial part of organizing an Angular application. They provide a way to group related components, directives, pipes, and services.

App Module (app.module.ts)

Here's a breakdown of the app.module.ts file:

typescript
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; import { HelloWorldComponent } from './hello-world/hello-world.component'; @NgModule({ declarations: [ AppComponent, HelloWorldComponent ], imports: [ BrowserModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
  • @NgModule: A decorator that marks a class as an Angular module and provides metadata about the module.
    • declarations: Declares the components, directives, and pipes that belong to this module.
    • imports: Other modules whose exported classes are needed by component templates declared in this module.
    • providers: The services used by the module.
    • bootstrap: The root component that Angular creates and inserts into the index.html host web page.

Data Binding in Angular

Angular provides powerful data binding features to synchronize data between the model and the view.

  1. Interpolation: Binding a component property to the template.

    html
    <p>{{ message }}</p>
  2. Property Binding: Binding a DOM property to a component property.

    html
    <input [value]="message">
  3. Event Binding: Listening for DOM events and triggering component methods.

    html
    <button (click)="sayHello()">Click Me</button>
    typescript
    export class HelloWorldComponent { message: string = 'Hello, Angular!'; sayHello() { console.log(this.message); } }
  4. Two-Way Binding: Combines property and event binding using the ngModel directive (requires FormsModule).

    html
    <input [(ngModel)]="message">
    typescript
    import { FormsModule } from '@angular/forms'; @NgModule({ imports: [ BrowserModule, FormsModule ] })

Directives in Angular

Directives are used to extend HTML by providing new syntax or behavior to the DOM.

  1. Structural Directives: Change the structure of the DOM. Examples include *ngIf, *ngFor, and *ngSwitch.

    ngIf

    html
    <p *ngIf="isVisible">This is visible</p>

    ngFor

    html
    <ul> <li *ngFor="let item of items">{{ item }}</li> </ul>
  2. Attribute Directives: Change the appearance or behavior of an element. Examples include ngClass, ngStyle, and custom directives.

    ngClass

    html
    <p [ngClass]="{'active': isActive}">This is a paragraph</p>

    ngStyle

    html
    <p [ngStyle]="{'color': textColor}">This is a paragraph</p>

Services and Dependency Injection

Services in Angular are used to encapsulate business logic and data access. Dependency Injection (DI) is used to provide services to components or other services.

  1. Creating a Service

    Use Angular CLI to generate a new service:

    bash
    ng generate service data

    This command creates a new service named DataService in src/app/data.service.ts:

    typescript
    import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class DataService { getData(): string[] { return ['Data 1', 'Data 2', 'Data 3']; } }
    • @Injectable: A decorator that marks a class as available to the DI system. The providedIn: 'root' syntax registers the service at the root level, making it a singleton service.
  2. Using a Service in a Component

    Inject the DataService into a component:

    typescript
    import { Component, OnInit } from '@angular/core'; import { DataService } from './data.service'; @Component({ selector: 'app-hello-world', templateUrl: './hello-world.component.html', styleUrls: ['./hello-world.component.css'] }) export class HelloWorldComponent implements OnInit { data: string[] = []; constructor(private dataService: DataService) {} ngOnInit() { this.data = this.dataService.getData(); } }
    • constructor(private dataService: DataService): This syntax automatically injects the DataService into the component.
    • ngOnInit: A lifecycle hook called after the component is initialized. It’s a good place to initialize data.
  3. Displaying Data from a Service

    hello-world.component.html

    html
    <ul> <li *ngFor="let item of data">{{ item }}</li> </ul>

Angular Routing

Routing in Angular allows navigation between different views or pages.

  1. Setting Up Routes

    Define routes in the app-routing.module.ts file:

    typescript
    import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { HelloWorldComponent } from './hello-world/hello-world.component'; const routes: Routes = [ { path: 'hello', component: HelloWorldComponent } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }
  2. Using Router Outlet

    Add <router-outlet> to app.component.html:

    html
    <h1>Welcome to My Angular App!</h1> <nav> <a routerLink="/hello">Hello</a> </nav> <router-outlet></router-outlet>
    • <router-outlet>: Acts as a placeholder for the routed component’s content.
    • routerLink: A directive to bind a link to a specific route.
  3. Navigating to a Route

    Now, when you click the "Hello" link, it navigates to the HelloWorldComponent view.

Angular Forms

Angular provides two approaches to handling forms: reactive forms and template-driven forms.

  1. Template-Driven Forms

    • Use Angular's directives to manage forms directly in the template.
    • Simpler and suitable for simple forms.

    app.module.ts

    typescript
    import { FormsModule } from '@angular/forms'; @NgModule({ imports: [ BrowserModule, FormsModule ] })

    hello-world.component.html

    html
    <form #myForm="ngForm" (ngSubmit)="onSubmit(myForm)"> <label for="name">Name:</label> <input type="text" id="name" name="name" ngModel required> <button type="submit">Submit</button> </form>

    hello-world.component.ts

    typescript
    onSubmit(form: any) { console.log(form.value); }
  2. Reactive Forms

    • Use FormGroup and FormControl classes to manage forms programmatically.
    • More powerful and scalable for complex forms.

    app.module.ts

    typescript
    import { ReactiveFormsModule } from '@angular/forms'; @NgModule({ imports: [ BrowserModule, ReactiveFormsModule ] })

    hello-world.component.ts

    typescript
    import { Component, OnInit } from '@angular/core'; import { FormGroup, FormControl, Validators } from '@angular/forms'; export class HelloWorldComponent implements OnInit { myForm: FormGroup; ngOnInit() { this.myForm = new FormGroup({ name: new FormControl('', Validators.required) }); } onSubmit() { console.log(this.myForm.value); } }

    hello-world.component.html

    html
    <form [formGroup]="myForm" (ngSubmit)="onSubmit()"> <label for="name">Name:</label> <input type="text" id="name" formControlName="name"> <button type="submit">Submit</button> </form>

Angular Pipes

Pipes are used to transform data for display in templates. Angular provides built-in pipes like date, currency, and uppercase.

  1. Using a Built-in Pipe

    html
    <p>{{ today | date }}</p>
  2. Creating a Custom Pipe

    Generate a custom pipe using Angular CLI:

    bash
    ng generate pipe custom

    custom.pipe.ts

    typescript
    import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'custom' }) export class CustomPipe implements PipeTransform { transform(value: string): string { return value.toUpperCase(); } }

    hello-world.component.html

    html
    <p>{{ message | custom }}</p>

Advanced Topics

To become a professional Angular developer, you should also explore these advanced topics:

  1. State Management: Learn about state management libraries like NgRx and Akita for managing application state.
  2. Lazy Loading: Improve performance by loading modules only when needed.
  3. Testing: Write unit tests for components and services using Jasmine and Karma.
  4. Angular Universal: Implement server-side rendering for SEO and performance benefits.
  5. Security: Understand Angular’s security features to protect your application from threats like XSS and CSRF.
  6. Performance Optimization: Learn about techniques like Change Detection Strategy, OnPush, and Ahead-of-Time (AOT) compilation to optimize performance.
  7. Internationalization (i18n): Implement multi-language support in your application.

Resources

  • Angular Documentation: The official Angular documentation is a comprehensive resource for learning Angular concepts and APIs.
  • Angular Blog: Stay updated with the latest Angular news and updates.
  • Online Courses: Platforms like Udemy, Coursera, and Pluralsight offer in-depth Angular courses.
  • Community: Join Angular communities and forums to connect with other developers and learn from their experiences.

By following this guide and exploring the advanced topics, you'll gain a solid understanding of Angular and be well on your way to becoming a professional Angular developer. Let me know if you have any questions or if there's a specific topic you'd like to explore further!

Post a Comment