kpidiba / angular_learning

Angular Learning repository

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

ANGULAR

DESCRIPTION

Angular (communément appelé « Angular 2+ » ou « Angular v2 et plus »)2,3 est un framework pour clients, open source, basé sur TypeScript et codirigé par l'équipe du projet « Angular » chez Google ainsi que par une communauté de particuliers et de sociétés. Angular est une réécriture complète d'AngularJScadriciel construit par la même équipe. Il permet la création d’applications Web et plus particulièrement d'applications Web monopages : des applications Web accessibles via une page Web unique qui permet de fluidifier l’expérience utilisateur et d’éviter les chargements de pages à chaque nouvelle action. Le framework est basé sur une architecture du type MVC et permet donc de séparer les données, le visuel et les actions pour une meilleure gestion des responsabilités. Un type d’architecture qui a largement fait ses preuves et qui permet une forte maintenabilité et une amélioration du travail collaboratif.

CONTENT

RESSOURCES

TEMPLATES

ANGULAR LAST VERSION

  • INSTALL NVM

  • nvm install 12.18.3(node version) or nvm install latest

  • nvm use 12.18.3

  • nvm list available

CREATE PROJECT

ng new project_name
or
ng new myProject --skip-install=true
cd myProject
npm install

MIGRATION WEBSITE

DESCRIPTION

Certainly, Angular is a comprehensive framework for building dynamic web applications. Here are some key concepts and features in Angular:

  1. Components: Angular applications are built using components. A component is a self-contained unit that encapsulates the view, logic, and data for a part of the user interface.

  2. Templates: Templates define the structure of how a component's view should be rendered. They use Angular's template syntax, which extends HTML with additional features like data binding and directives.

  3. Directives: Directives are instructions in the DOM that tell Angular how to render the UI. They can be structural (like ngIf and ngFor) or attribute-based (like ngModel).

  4. Data Binding: Angular supports various types of data binding that enable you to synchronize data between the component and the view. Types of data binding include Interpolation, Property Binding, Event Binding, and Two-way Binding.

  5. Services: Services provide a way to share data and functionality across components. They are usually used to handle data retrieval, manipulation, and communication with the backend.

  6. Dependency Injection: Angular's dependency injection system is used to provide instances of services, components, and other objects to the parts of your application that need them. This promotes modularity and reusability.

  7. Modules: Angular applications are modular, and modules are used to group related components, directives, pipes, and services together. The main application module is often referred to as the root module.

  8. Routing: Angular's router allows you to create a single-page application with multiple views. You can define routes, navigate between them, and load different components based on the URL.

  9. Forms: Angular provides two types of forms: template-driven forms and reactive forms. Forms allow you to capture user input and validate it before submitting it to the server.

  10. HTTP Client: The HttpClient module is used to make HTTP requests to a server. It supports features like request/response transformations, error handling, and interceptors.

  11. Pipes: Pipes are used to transform data for display in the template. Angular provides built-in pipes for formatting dates, numbers, and more. You can also create custom pipes.

  12. Interceptors: As discussed earlier, interceptors are used to intercept HTTP requests and responses to add common functionalities.

  13. Lifecycle Hooks: Components have lifecycle hooks that allow you to tap into various stages of a component's lifecycle, such as ngOnInit, ngOnChanges, and ngOnDestroy.

  14. Modules and Lazy Loading: Angular supports lazy loading, where you can load modules on-demand, improving initial loading time. This is particularly useful for larger applications.

  15. Testing: Angular applications can be thoroughly tested using tools like Jasmine for unit testing and Protractor for end-to-end testing.

  16. Internationalization (i18n): Angular provides tools for internationalizing your application, allowing you to support multiple languages and locales.

  17. Animations: Angular provides a powerful animation system to create smooth transitions and effects in your application.

  18. State Management: While not a core Angular concept, many Angular applications use libraries like NgRx or Akita for managing application state in a more controlled manner

CONCEPTS

  • Angular is a popular JavaScript framework for building web applications. It provides a comprehensive set of features and concepts that enable developers to build robust, scalable, and maintainable applications. Here are some key concepts in Angular:

    1. File Architectures , setup

    2. Components: Components are the building blocks of an Angular application. They encapsulate the UI and behavior of a part of the application. Each component has its template, styles, and logic. Components are organized in a component tree hierarchy.

    3. Templates: Templates define the structure and layout of the component's view. They use HTML combined with Angular-specific template syntax, such as data binding, directives, and event binding, to render dynamic content.

    4. Directives: Directives are markers on DOM elements that allow you to extend HTML with custom behaviors and manipulate the DOM. Angular provides built-in directives like ngIf, ngFor, and ngStyle, and you can also create your own custom directives.

    5. Data Binding: Data binding enables the synchronization of data between the component and its template. Angular supports different types of data binding, including interpolation ({{ }}), property binding ([ ]), event binding (( )), and two-way binding ([( )]).

    6. Services: Services are reusable components that provide specific functionality and can be shared across multiple components. They are responsible for handling data, performing HTTP requests, and implementing business logic. Services are typically injected into components using dependency injection.

    7. Dependency Injection: Dependency injection is a design pattern used in Angular to manage the dependencies between different components and services. Angular's dependency injection system allows you to declare dependencies in the constructor of a component or service and have them automatically resolved and provided by the framework.

    8. Routing: Angular's router enables navigation between different views/components based on the application's URL. It allows you to define routes, associate them with components, and handle navigation events.

    9. Modules: Modules are used to organize and encapsulate related components, services, and other Angular features. They help to keep the application modular, improve code organization, and enable lazy loading of parts of the application.

    10. Forms: Angular provides powerful form handling capabilities, including template-driven forms and reactive forms. Form controls, validators, and form submission handling are some of the features offered by Angular's forms module.

    11. Observables: Observables are a fundamental part of Angular's reactive programming approach. They represent streams of data over time and are used extensively for handling asynchronous operations, such as HTTP requests and event handling.

    12. Standalone: Angular Standalone is a way to build Angular applications that do not use NgModules. NgModules are a core concept of Angular, and they provide a way to organize your code and dependencies. However, they can also add complexity to your applications.

      Angular Standalone aims to simplify the authoring experience by reducing the need for NgModules. Standalone components, directives, and pipes are simply declared as JavaScript modules. They do not need to be imported into an NgModule, and they do not have access to the NgModule's services.

      This can make it easier to write and maintain your code, especially if your application is small or simple. It can also make it easier to share components, directives, and pipes between applications.

      To use Angular Standalone, you need to add the @angular/core:standalone schematic to your project. This schematic will convert all of your components, directives, and pipes to standalone mode.

      You can also choose to migrate an existing Angular project to standalone mode. To do this, you need to run the ng g @angular/core:standalone schematic multiple times. The first time, you will select the "Convert all components, directives and pipes to standalone" option. The second time, you will select the "Remove unnecessary NgModule classes" option. The third time, you will select the "Bootstrap the project using standalone APIs" option.

    13. Signals : Les signaux Angular sont des primitives réactives qui permettent de définir des valeurs réactives et d'exprimer les dépendances entre elles. Ils sont basés sur le modèle d'observateur, ce qui signifie qu'ils peuvent être utilisés pour observer des valeurs et être avertis lorsqu'elles changent.

      Les signaux Angular sont utilisés pour améliorer les performances des applications Angular en réduisant le nombre de fois où le moteur de changement doit être exécuté. Lorsque le moteur de changement est exécuté, il s'assure que l'interface utilisateur reflète l'état de l'application. Les signaux Angular peuvent être utilisés pour empêcher le moteur de changement d'être exécuté lorsque les valeurs ne changent pas.

      Les signaux Angular sont également utilisés pour améliorer la lisibilité du code Angular. En utilisant des signaux, les développeurs peuvent indiquer clairement les dépendances entre les valeurs, ce qui rend le code plus facile à comprendre et à maintenir.

    14. Route child nested :

FRAMEWORK

  • Framework generally contains set of libraries

  • You can extend framework

ANGULAR SPRING BOOT

  1. RESTful API: Spring Boot provides robust support for building RESTful APIs. With Angular, you can consume these APIs to fetch and manipulate data from the server. Understanding how to define and consume RESTful APIs in Spring Boot is crucial for seamless integration with Angular.

  2. CORS (Cross-Origin Resource Sharing): Since Angular typically runs on a different domain/port than the Spring Boot backend, you need to configure CORS to allow requests from the Angular frontend to access the Spring Boot API. CORS defines how the browser enforces security by restricting cross-origin requests. You can configure CORS in Spring Boot to specify which origins, HTTP methods, and headers are allowed.

  3. Security: Authentication and authorization are important aspects of most web applications. Spring Security is a powerful security framework that integrates well with Spring Boot. You can leverage Spring Security to secure your backend APIs and handle authentication and authorization in your Angular application.

  4. DTO (Data Transfer Object): It is common to use Data Transfer Objects to transfer data between the Angular frontend and the Spring Boot backend. DTOs help in defining a specific structure for data transmission and decoupling the frontend and backend models.

  5. Interceptors: Angular interceptors allow you to intercept HTTP requests and responses. You can use interceptors to add headers, handle authentication tokens, or perform other custom logic. In the case of Angular and Spring Boot integration, you can use an interceptor to attach an authentication token to each request made from Angular to the Spring Boot API.

  6. JWT (JSON Web Tokens): JSON Web Tokens are a popular approach for handling authentication and authorization in modern web applications. You can use JWTs in combination with Spring Security to authenticate users in your Spring Boot backend and pass JWT tokens to Angular for subsequent API requests.

  7. Deployment: Angular and Spring Boot applications can be deployed separately or together. You may need to configure your server to serve both the Angular frontend and Spring Boot backend. Understanding the deployment process and configuring the server to correctly handle both Angular and Spring Boot can help ensure a smooth deployment experience.

SETUPS

  • install node js

  • npm install -g @angular/cli

  • ng new Welcome

FILE ARCHITECTURE

The application project files are placed in the in the src/ folder of the workspace. The src/ folder contains the source files for the root application. Let’s now look at the content of the src/ folder

app/ – this folder contains the where the application logic and data are defined.

assets/ – this folder contains assets including images used by the application

environment/ – contains build configuration settings for a particular target environment. There is a default standard production environment

index.html – this is the index page of the web application. The script and css files are added automatically.

main.ts – this is the main entry point of the application. It compiles the application with the Just-In-Time(JIT) compiler and bootstraps the root module(AppModule) to run in a browser.

styles css – This files contains the css styles and stylesheets that  are used by the project.

3. Content of the app/ Folder

The key project files you’ll be working with in located in the app/ directory inside the src/ folder. The file files inside include the following:

app.component.css – this is the css style for the root AppComponent. The styles here applies to the app.component.html file

app.component.html – this is the html template associated with the root component (AppComponent0

app.component.specs.ts – Use for unit testing of the root component

app.component.ts – This a TypeScript file that defines the core logic of the AppComponent. The view associated with the AppComponent is what becomes the root of the view hierarchy as you add components and services  to your application.

app.module.ts – this file defines the root module of the application. The root module is called AppModule. This tell Angular how to organise your application. Any new components you will be adding to your application must be defined in the app.module.ts file.

app.routing.module.ts – this file contains the definitions for the navigation between components in Angular application

COMMANDS

  • Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
  • change port: ng serve --port 3000

ENVIRONMENTS

LIBRARY

  • Library generally perform specific operation

  • You can build mutiple libs to build apps

SPA(Singe Page Application)

 is a web app implementation that loads only a single web document, and then updates the body content of that single document via JavaScript APIs such as XMLHttpRequest and Fetch when different content is to be shown.

  • SPA does not make requests to server for every URL requests

  • Generalement on cree plusieurs pages pour chaque vue

  • Ressource are on client browser

MODULES

in Angular, a module is a mechanism to group components, directives, pipes and services that are related, in such a way that can be combined with other modules to create an application. An Angular application can be thought of as a puzzle where each piece (or each module) is needed to be able to see the full picture.

components

The component is a combination of data html   template and logics    .

The component represent an area of a view that shows inside the browser. The component are loads inside the browser

  • create componentt for every component(side bar,nav bar)

  • selector (convention name : app-{component name}),indentify the component

  • generate with component with angular cli

ng g c component_name
  • component_name.component.spec.ts (pour les test unitaires)

  • app.module.ts (import components)

DIRECTIVE TYPES

Directives are meant to be a function that executes when found in the DOM by the Angular compiler to extend the power of the HTML with new syntax

  • Component directive(    directive with template view)

  • Structural directive (which can change the DOM layout by adding and removing DOM elements)

  • Attribute Directive (we can change appearance or behavior of an element,component or another directive)

  • custom directive (create own custom directive)

  • ng For :render array inside a view ,structural directive ,manipulate DOM.

//for array
<li *ngFor="let post of listPost">{{ post }}</li>
//for object
<li *ngFor="let obj of listObject">{{ obj  | json }}</li>
  • ngIf(STRUCTURAL)
<div *ngIf="listPost.length > 0 "></div>
  • ngTemplate (STRUCTURAL)
<ng-template #emptyList>
    <p>there is no data in list post</p>
</ng-template>


<h3>List Object</h3>
<div *ngIf='listObject.length > 0; else emptyList' >
  <ul>
    <li *ngFor="let obj of listObject;let i = index">
      index:{{ i }}  name:{{ obj.name }}
      <button (click)="onDelete(obj,i)">delete</button>
    </li>
  </ul>
</div>
  • ngSwitchCase
<button (click)="sendStep('step 1')">Step 1</button>
<button (click)="sendStep('step 2')">Step 2</button>
<button (click)="sendStep('step 3')">Step 3</button>

<div [ngSwitch]="stepForm">
  <div *ngSwitchCase="'step 1'">Step 1 Form</div>
  <div *ngSwitchCase="'step 2'">Step 2 Form</div>
  <div *ngSwitchCase="'step 3'">Step 3 Form</div>
  <div *ngSwitchDefault>Something Else Default</div>
</div>
  • ngStyle (ATTRIBUTE)
<h3 [ngStyle]="{
  color:boolColor? 'blue':'orange',
  textTransform:boolColor?'uppercase':'lowercase'
}">style changing</h3>
  • ngClass (ATTRIBUTE)
[ngClass] = "{
    'main':isActive,
    'text-weight':isActive
}"

DATA BINDING

create variable in component.ts and use {{ }} to show the value in html or other

SHARE DATA BETWEEN COMPONENT

  • Parent to Child Component via @input Decorator
//child ts file
@Input() parent_value:string;
  constructor() {
    this.parent_value ="";
}
//in parent declare value
//using it in html
<child_name [parent_value]='parent_value' ></child_name>
  • Child to Parent Component via @ViewChild Decorator
class IMPlements AfterViewInit{
//import child_name.component.ts and add to viewchild
@ViewChild(PostComponent) childCompo: any;
//init value with this
ngAfterViewInit(): void {
    console.log(this.childCompo);
    this.message_child = this.childCompo.childVar;
  }
  • Child to Parent when there is Event ,using the @Output Decorator and Event Emitter
//in child view
@Output() message_event = new EventEmitter<string>;
sendMessage() {
    this.message_event.emit(this.secondChildM);
 }.
//in child html
<button (click)="sendMessage()" >Event button</button>
//in parent html
<app-post [parent_value]='parent_value' (message_event)="receiveMessage($event)" ></app-post>
receiveMessage($event:string){
    console.log($event);
  }
  • component is a parent of a component that the contains

DISPLAY DATA

  • STRING INTERPOLATION: {{ }} creer une variable dans la classe et l' afficher dans le fichier html

PROPERTY BINDING

<img [src]="imageUrl" alt="property binding">

CLASS BINDING

Exemple:create text-red class in css and put color:red;

<h4  [class.text-red] = "boolColor" >fromchild :{{ fromChildValue }}</h4>
//declare boolColor as Boolean with value false
boolColor:bool = true;

STYLE BINDING

  • ressources Dom style in w3school website
<h1 [style.backgroundColor]=" boolColor ?'red':'green'">Angular Root Tag</h1>

EVENT BINDING

<button (click)='sendMessage()' >Click</button>
  • event filter: $event

TEMPLATE VARIABLE

  • declare template variable with #variable_name
//in html
<input (keyup)="onKeyUp(username)" #username >
//in ts
onKeyUp(value:HTMLInputElement){
    console.log("value: "+value.value);
 }

TWO WAY BINDING

import { FormsModule } from '@angular/forms';
//add FormsModule to app.module.ts , import
<input type="text" [(ngModel)] = "twoWayBinding">

ONE WAY DATA BINDING vs TWO WAY DATA BINDING

  • ONe way

Can only binding data component to view

component ----unidirectionel ---> view (html)
  • two way , view and modify

CHANGE DETECTION

STRUCTURAL VS ATTRIBUTE DIRECTIVES

  • STRUCTURAL DIRECTIVES :

    • We can manipulate the DOM by adding and removing HTML Elements to the DOM

    • With the ***** we can easily Identify a Structural Directive

    • NgFor,NgIf,NgSwitch

  • ATTRIBUTE DIRECTIVES

    • change appearance or the behavior of a DOM Element

    • NgClass ,NgStyle

ANGULAR PIPES

It used to transforming data into a particular format when we only  need that data transformed 'in' a template.

  • Uppercase Pipe

  • Lowercase pipe

  • Decimal/Number pipe

  • Date pipe

  • Json Pipe

  • Percent Pipe

  • Slice Pipe

{{ pipv | uppercase }}
{{ count | number }}
{{ dcount | number:'2.3-4' }}
{{ count | currency:'JPY' }}
{{ count | currency:'EUR' }} <br>
{{ "date:"+today | date }}
{{ davidO | json }} 
{{ 0.2345| percent }}
//custom pipe
- create folder
import {Pipe , PipeTransform} from '@angular/core'


@Pipe({
  name: 'summary'
})
export class SummaryPipe implements PipeTransfrom{
    transfrom(value:string,length:number):unknow{
    if(!length ){
        length = 20;
    }
    return value.substring(0,length);
}
}
}

DATE BINDING

List of all predefined date formats in Angular

Date Format Angular datepipe code Result
M/d/yy, h:mm a {{todayDate | date:'short'}} 6/15/19, 10:54 PM
MMM d, y, h:mm:ss a {{todayDate | date:'medium'}} Jun 15, 2019, 10:54:25 PM
MMMM d, y, h:mm:ss a z {{todayDate | date:'long'}} June 15, 2019 at 10:54:25 PM GMT+5
EEEE, MMMM d, y, h:mm:ss a zzzz {{todayDate | date:'full'}} Saturday, June 15, 2019 at 10:54:25 PM GMT+05:30
M/d/yy {{todayDate | date:'shortDate'}} 6/15/19
MMM d, y {{todayDate | date:'mediumDate'}} Jun 15, 2019

dd MMMM yyyy: 15 Mars 2003

ngOnInit vs ngAfterViewInit

  1. ngOnInit:

    • The ngOnInit lifecycle hook is called once when the component is initialized after its constructor. It is commonly used to perform component initialization tasks.
    • This hook is useful for initializing component properties, making API calls to fetch initial data, subscribing to observables, and setting up the component's initial state.
    • At the time ngOnInit is called, the component's inputs and properties are available, but the view (DOM) may not have been rendered yet.
  2. ngAfterViewInit:

    • The ngAfterViewInit lifecycle hook is called after the component's view (DOM) has been fully initialized and rendered.
    • This hook is useful when you need to access and manipulate the DOM elements or perform any tasks that require the view to be fully rendered.
    • It is commonly used for interacting with child components, manipulating the view's rendered elements, setting up third-party libraries that require access to the DOM, or initializing plugins.
    • It is important to note that ngAfterViewInit is not called for components that are not part of the current view hierarchy (e.g., components within *ngIf or *ngFor blocks that are not currently rendered).

In summary, ngOnInit is called once during component initialization and is typically used for component initialization tasks, while ngAfterViewInit is called after the component's view is fully rendered and is often used for manipulating the DOM or interacting with child components.

Angular Services

Angular services are utilized to share data among components, whether there is a relationship between components or not.

  • Manually Creating Services:

    • Create a folder named services and within it, create a file named post.service.ts.
export class PostService {
    postList: Array<any> = [{}];
}

constructor(private postService: PostService) {
    this.posts = postService.postList;
}
  • Creating Services with Angular CLI:

    • Generate a service using Angular CLI with the following command:
ng generate service services/service_name

GUARDS COMMAND

Angular route guards are interfaces provided by Angular which, when implemented, allow us to control the accessibility of a route based on conditions provided in class implementation of that interface. Here are some types of Angular guards: CanActivate, CanActivateChild, CanLoad, CanDeactivate and Resolve.

ng g guard services/auth-service/auth

DEPENDENCY INJECTION

  • TO USE IT
  constructor(private router:Router) {
  }
  router = inject(Router)
  • first method: define service class as provider in app.module.ts ,or in direct component ts file
providers: [PostService],
  • second method: make service injectable to any component
//in service class
@Injectable({
    providedIn: 'root',
})
// THE SECOND :define in provider
@Injectable({
})
  • generate manually service
ng g s services/test
  • generate manually interface
ng g i models/user

ANGULAR DRIVEN FORM

  • two form types (reactive form and template driven form z)

  • go to form and form-b component to seed codes

  • all are in form component

  • FormControll errors

class FormControll{
    value();
    touched();
    untouched();    
    dirty();
    pristine();
    valid();
    errors();
}
  • REACTIVE FORM

    • import in app.module.ts
ReactiveFormsModule    
this.myForm.controls['firstName'].valueChanges.subscribe(value => {
  console.log(value);
});

CUSTOM VALIDATIONS

  • create validators folders

  • name example : nospace.validators.ts

import { AbstractControl, ValidationErrors } from "@angular/forms";

class noSpace {
    noSpaceValidations(control:AbstractControl):ValidationErrors|null{
        let controlValue = control.value as string;
        if(controlValue.indexOf(' ') >= 0){
            return {noSpaceValidations:true};
        }else{
            return null;
        }
    }
}

ROUTING

Navigate throw components

  • First method: declare in app.module.ts
RouterModule.forRoot([
      {path:'post',component:PostComponent},
       {path:'postlist',component:PostListComponent}
      {path:'**',component:NoMatchComponent}
    ]),
  • Router-Outlet is an Angular directive from the router library that is used to insert the component matched by routes to be displayed on the screen

  • routeLink (for redirect): don't loading the page

<button style="margin: 10px;" routerLink="postlist" routerLinkActive="active">Post list</button>
<button [routerLink] = "['/post',index]">View content</button>
  • Navigation in ts file programmaticaly
this.router.navigate('/posts');
  • multi parameter
<button [routerLink]="['/single',1,'man']">Cliquer</button>
  • second method: common, put route on a modules file and put routes in the file
ng g module app-routing --module name_of_module --flat

RXJS

  • RXJS is a library for composing asynchronous and event-based programs by using observable sequences. It provides one core type, the Observable, satellite types (Observer, Schedulers, Subjects) and operators inspired by Array methods ([map](https://rxjs.dev/api/index/function/map), [filter] (https://rxjs.dev/api/index/function/filter), [reduce] (https://rxjs.dev/api/index/function/reduce), [every] (https://rxjs.dev/api/index/function/every), etc) to allow handling asynchronous events as collections.

  • DOCUMENTATION: RxJS

  • An Observable is a sequence of data that is emitted data asynchronously or synchrounsly over a time of period, It will continously observe a set of stream data & automatically update or track that sequence of data whenever there is something changed

import {
  AfterViewInit,
  ChangeDetectorRef,
  Component,
  OnInit,
  ViewChild,
} from '@angular/core';
import { FormControl } from '@angular/forms';
import { FormComponent } from './form/form.component';
import { PostComponent } from './post/post.component';
import { Observable } from 'rxjs';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
  constructor() {}
  ngOnInit(): void {
    const obsTest = new Observable((observer) => {
      //NOTE: can return many data
      observer.next('Returned of observalble');
      observer.next('Returned of observalble one');
      observer.next('Returned of observalble two');
      console.log('printed from observable');
    }).subscribe((value) => console.log(value));
    obsTest.unsubscribe();
  }
}    

About

Angular Learning repository


Languages

Language:JavaScript 53.9%Language:TypeScript 46.1%