####### Introduction to Angular ######
##Angular (ng) High-level info (Angular 7)
Angular 2+ (‘Angular’) is a Typescript-based opensource front-end web application platform (originally from Google)
TypeScript (.ts) => String Typing, Decorators (Annotations)
--> ES6 (ECMAScript) => Classes, Modules, Arrow Functions
TypeScript Compiler generates Java Script (human-readable) --> Compile in to ES5 or ES6
SPA - Single Page Application
- AJAX & HTML5 - HTML Fragments (mini--views)
Clean separation of code that renders UI & the code that does the application Logic
Dependency Ingection - loose coupling b/w components and services
Automatic change detection (UI gets reflected automatically)
Comes with Rx.js - subscriptionbased processing of asynchronous data - eliminated callback hell
Angular CLI - The scaffolding and deployment tool - spares developers from writing the boilerplate code and configuration scripts.
##Responsive Web Design (RWD)
- Web desgin approach - optimal viewing experiance on wide range of devices
- Responsive theme's layout adjusts to your devices screen size
##WorkSpace Setup
Node-v10.x https://nodejs.org/en/download/
Visual Studio Code
Angular CLI - npm install -g @angular/cli
##First Project (ng way)
#1 Open Terminal window --> go to your folder where you want to create the project
--> ng new <<your-project-name-here>>
#2 Launch the Angular application by running the command
--> ng serve --o
#3 Launches the index.html in a browser @ http://localhost:4200 (port might vary)
##Deployment and other info - https://angular.io/guide/deployment
##Build and Deploy as a JS
Ng serve
• In-memory compilation running on local server
• File changes trigger reload for iterative development
Ng build
• Creates output folder ‘dist’
• Consolidates app into a few js files
• Assets folder replicated
• Must change base href for deployment environment
##First Project (npm way)
Go to desired folder in Terminal and run --> npm init -y
look at files, especially package.json
Add dependencies – Angular, SystemJS, Live-server, TypeScript compiler
Run the install command to install the above dependencies --> npm install
Copy the following files
- SystemJS Config file, index.html, main.ts, app.module.ts and app.component.ts
Launch the Angular application by running the command
Launch the index.html in a browser @ http://localhost:4200/index.html (port might vary)
## Angular Project Structure
#Angular.json
"outputPath" is the location where the ng build command places the condensed js files for the entire app
index.html is the single page in which the Angular App is injected
main.ts is the “main” Angular entry point
polyfills.ts contains browser compatibility polyfills and application polyfills.
styles.css is where global styles can be placed. Any CSS rules you place here are injected into the DOM in a <style></style> tag
"assets" array describes the location of static file assets
#Index.html
#main.ts --> calls bootstrap function
#app.module.ts --> being bootstrapped - to app component
#app.component.ts --> @Component decorator
#app.component.html -->
################ Basic Concepts and Binding ##########
Used along with the ngModel object.
*Must Import FormsModule
<input [(ngModel)]="dynamicValue"placeholder="Watch the text update !"type="text"><span>{{dynamicValue}}</spn>
## Component
Components form the building blocks of an Angular application.
To create a Component, issue the following command
ng g component <component name>
#Practice
1. Make Developer Class (ng g class Developer)
1. firstName: string
2. lastName: string
3. favoriteLanguage: string
4. yearStarted: number
2. Make new component called ‘bio’ (ng g component bio)
1. Import Developer Class
2. Create instance of a developer inside of the constructor
assign to a property called ‘dev’
3. Display dev component in bio.component.html
4. Add <app-bio></app-bio> to app.component.html
5. Create toggle switch using ngIF to only display bio component
if link is clicked
Use the "selector" value of the new component in the app.component.html to import it there
## Component Lifecycle
• The lifecycle of a component is managed by Angular itself.
• It manages creation, rendering, binding data-bound properties etc. and also
offers the feature “hooks” that allows responding to key lifecycle events.
• Here is the complete lifecycle hook interface inventory:
• ngOnChanges - called when an input binding value changes.
• ngOnInit - called after the first ngOnChanges.
• ngDoCheck - called after every run of change detection.
• ngAfterContentInit - called after the component content is initialized.
• ngAfterContentChecked - called after every check of component content.
• ngAfterViewInit - called after the component's view(s) are initialized.
• ngAfterViewChecked - called after every check of a component's view(s).
• ngOnDestroy - called just before the component is destroyed.
## Elvis Operator:
• If a property, that does not exist, is referenced in a template, an
exception is thrown.
• The “Elvis Operator” is a simple and easy way to guard against null and
undefined properties.
• It is denoted by a question mark immediately followed by a period “?.”.
<md-input-container>
<label>Type to see the value</label>
<input md-input type="text" />
</md-input-container>
<strong>{{input?.value}}</strong>
## Structural Directives
• ngIf adds and removes elements in the DOM based on the
results of an expression.
• ngFor is a repeater directive that outputs a list of elements by
iterating over an array.
<div *ngIf="emps">
<div *ngFor="let emp of emps">
<p><span class="bold">First Name:</span> {{emp.firstName}}</p>
<p><span class="bold">Last Name:</span> {{emp.lastName}}</p>
<p><span class="bold">Department:</span> {{emp.department}}</p>
<hr />
</div>
</div>
## Introduction to Routes
• Routing allows to:
– Recover browser history functionality which is otherwise lost with SPA
– Maintain the state of the application.
– Implement modular applications.
– Implement the application based on the roles (certain roles have access to
certain URLs).
• Routes are injected into <router-outlet></router-outlet>.
This is most commonly placed in app.component.html below any navigation bars or content
that you want to appear on every page
You can add routing after the fact
• Angular best practice is to create a separate, top-level module dedicated to routing
ng g module app-routing --flat --module=app
• - - flat flag will place the module in the top level
• - - module=app will add the import for app-routing inside of AppModule
## Route Configuration
Routes are configured, using the Routes type, which is an array of route objects.
The route object is composed of the following attributes:
– Path: URL to be shown in the browser when application is on the specific
route.
– Component: Component to be rendered to, when the application is on the
specific route. This is the output of the router link.
##app-routing.module.ts## sample
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { EmpComponent } from './emp/emp.component';
const routes: Routes = [
{path:'', component: HomeComponent},
{path:'bio',component:EmpComponent}];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
## redirectTo ## Routes may redirect to other routes, using the redirectTo attribute.
const routes: Routes = [
{ path='', redirectTo= 'emp', pathMatch ='full' },
{ path='emp', component:EmpComponent }];
##Route Navigation##
• In the view template, routerLink directive may be used inside of
an anchor tag to add links that point to the defined routes.
<a routerLink:"/component-one" > Component One </a>
#Programatically do it this way
import {Router} from '@angular/router';
constructor (private router: Router){}
this.router.navigate("/emp")
## BootStrap Stylesheet - industry standard style for Angular
<!-- google for bootstrap style sheet link to get below link -->
<!-- Add below link under head section of index.html -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
## Services in Angular ##
• Create a Service using the command:
ng g service <<ServiceName>>
• Services expose methods (supposedly business logic) as
API along with optional public properties.
• Services are dependencies injected by Angular, which
maintains each service as a singleton.
• The @Injectable decorator is used to mark a Typescript
class as a Service.
• providedIn: Determines which injectors will provide the
injectable, by either associating it with an @NgModule or
other InjectorType, or by specifying that this injectable
should be provided in the 'root' injector, which will be the
application-level injector in most apps
## Injectable Decorator
## Dependency Injection
• Import the service class
• Define it within the constructor parameters
• It should have the ‘private’ access modifier
## Route Parameters
Parameters are sent using :paramName embedded on to the router paths:
const routes: Routes = [
{ path='', redirectTo= 'product-list', pathMatch ='full' },
{ path='product-details/:id', component: ProductDetails }];
The parameter can then be sent using routerLink and interpolation:
<a routerLink="product-details/{{product.id}}"> {{product.name}} </a>
OR the routerLink directive may be used and supplied with parameters
to be automatically sent, while invoking a router link.
<a *ngFor="let product in products"
[routerLink]="['/product-details', product.id]">
{{product.name}}
</a>
## Reading Routing Parameters using ActivatedRoute ##
– Angular provides the ActivatedRoute service, which in turn supplies
a paramMap property which contains the parameters.
import {ActivatedRoute} from '@angular/router';
@Component.....
export class TestComponent implements onInit{
id;
constructor(private route: ActivatedRoute){}
ngOnInit(){
this.id = this.route.snapshot.paramMap.get('id')
}
}
## Navigate to parameterized routes via code
Navigating to parameterized routes internally:
– Create a Router object and use the navigate method.
– Pass an array containing the main route and the parameter
(just like routerLink directive on previous page)
@Component ....
export class TestComponent{
constructor(private router: Router){}
goToProductDetails(id){
this.router.navigate('/product-detail', id);
}
}
## Creating in app-routing.module.ts
## Linking
## Retrieving parameters in component class
## Child Routes
================================================