I: Development environment preparation
Download and install angular
, webpack, scaffolding
ferret outnodeVersion:node -v
Angular8Only supportnode10previous version
ferret outnpmVersion: npm -v
Remove the old version of angular installed: cnpm uninstall -g @angular/cli
Remove angular installer
Clear the cache:npm cache clean --force
Install the latest version of angular globally: cnpm install -g @angular/cli@latest
Check if the installation was successful: ng version
gnvmManaging nodes
Download it and put it in the path where you installed node, double click and run it.
Run as administrator: gnvm version
- Download node with gnvm: gnvm install 6.13
- Download the latest version of node: gnvm update latest
- See which node versions are installed: gnvm ls
- Use a version: gnvm use 6.11.3
Create a project:ng new demo
Error: npm ERR code ERR_STREAM_WRITE_AFTER_END
Solution: Reduce the npm version: npm i -g[email protected] (there will be unsupported node 10.16.3warning)
Re-create again: ng new demo (under cmd)
Switch to the directory: cd demo
Run the project: ng serve -open(angular6 need node10 above)
II: Foundations
Components/Commands
Module/Routing
dependency injection
rxjs/Http
Components and component trees:
1.Creating Components
Create the header component in the components directory:.ng g component comments/header
2. Component content
Included in the component: html and css and ts
Composition of the document
classcomponent classrespond in singingdecorator@Component Composition
Decorator: gives the class richer metadata, inside which you can define the component'stemplatestemplate
@Component({
selector:'hello', //match hello tag
template:'<p>{{greeting}}</p>'//this template will be inserted into the hello tag
})
export class HelloComponent{
private greeting:string; // Attribute declarations
constructor(){
= 'Hello Angular 2'} // attribute assignment
}
4. Declaration and use of attributes and objects (in ts)
data type | herald | utilization |
causality | public name:any='Zhang San' | <div [title]=”name”> |
public name:string; | ||
constructor(){ = "Zhang San } | ||
boyfriend | public userinfo:object={ name:'Zhang San'. age:’20’ } |
{{}} |
5.Use of data (in html)
Interpolation: {{greeting}}
Data Binding: Property Binding, Event Binding, Bidirectional Binding
Type of binding | Contents | (for) instance |
Html Binding | public contant=’<div>123</div>’ <div [innerHTML]=’contant’> |
|
Class Binding | <div [ngClass]=”{ ‘box1’:ture }”> <li *ngFor=”let item of data1;let key=index” [ngClass]=”{red:key==0}”></li> |
|
Style Binding | <li [ngStyle]=”{‘color’:licolor}”></li> private licolor:ang=”red”; |
|
property binding | value | <input [value]=”myData”/> |
src | pubilc picUrl:string=”../../../assets/”; <img [src]=”picUrl”> |
|
event binding | Keyboard Events keydown |
keyDown(e){ console.log(e); (); (); } <input type=”text” (keydown)=”kayDown($event)”> |
Keyboard Events keyup |
keyUp(e){()} <input type=”text” (keyup)=”kayUp($event)”> |
|
mouse click event click |
// Fetch data on click public title:any="Original Title"; getData(){alert()} <button (click)="getData"> Click </button> |
|
// Setting data after clicking public title:any="Original title"; setData(){="Title changed"} <button (click)=”setData”> click </button> | ||
//Get the object after clicking getDom(e){var dom=;=”red”} <button (click)="getDom($event)" > click </button> | ||
two-way binding | <input [(ngModel)]=”myData”/> |
two-way binding
1. Import module
import {FormsModule} from ‘@angular/forms’
2.Module Registration
@NgModule({
imports:[FormsModule]
})
3. Use:
public keywords:any;
<input type=”text” [(ngModle)]=”keywords”>
{{keywords}}
Instructions and orders
Including attribute directives and structural directives, components are also a type of directive
Attribute directives: change the appearance or behavior of a component, such as styles
Structure directive: change the Dom structure of the template
directives |
(for) instance |
account for |
ng-app |
|
Initializing the application |
ng-init |
|
Initialization data |
ng-module |
|
Bind elements to the application |
ng-repeat |
|
Duplicate HTML elements |
ng-module |
<form name=’myForm’> <input type=’email’ ng-module=’myText’ name=’myAddress’> <p> click </p> {{.$valid}} {{ .$dirty}} </form> |
Binding the value of an input field to a variable can provide state values for application data. Invalid: ture if the input value is legal. dirty:The value changes to touched:By touching the screen to click for theture error: |
*ngFor |
// Data
|
ngFor is used as a loop |
ngSwitch | //Definition data public score:ang=”1” //Use: <ul [ngSwitch]=”score”> <li *ngSwitchCase="1"> paid</li> <li *ngSwitchCase="2"> Unpaid</li> <li *ngSwitchCase="false"> Payment failed</li> </ul> |
|
*ngIf | // Define the data: public flag:boolean=true; //Use <div *ngIf=”flag”><div> |
use |
command |
account for |
View angular version |
ng version |
|
Create a project |
ng new demo |
|
Running Projects |
ng serve –open |
|
What are the parameters for creating |
ng g |
|
Creating Components |
ng g component comments/header |
|
Services and Dependency Injection
Dependency Injection Providers: A mechanism for components to introduce external constructs (e.g. services).
Services: logical units that fulfill a single purpose, such as logging services
Service → Instantiation → Dependency Injection → Injection → Component
@component({
selector:’hello’,
template:’<p>greeting</p>’,
providers:[loggerService],
})
export class HelloCom1{
private greeting:string;
constructor(logger: loggerService){
=’hello angular’;
('Constructfunction (math.)Execution complete')
}}
module (in software)
Includes documentation and application modules
Documentation modules: framework code is organized in the form of modules , including core core modules ( transformation detection , dependency injection Component, Directive, ElementRef, Renderer , etc. ), comment general module ( commonly used built-in instructions ), forms form module ( form-related components and instructions ), http network module ( handling network requests) and others
Application Modules: Functional units in the form of modules, i.e., components, commands, services packaged
1. Introduction
import {Http} from ‘@angular/http’
2. Module definition
@NgModule({ //module declaration
declarations:[AppComponent,SomeDiretive], //wrapping instructions or components, etc.
providers:[loggerService], //dependency injection
imports:[OtherModule], //import other modules
bootstrap:[ AppComponent], //set the root component
exports:[SomeDirective], //export component or directive
})
export class AppModule {}
data processing
pipe
typology | (for) instance |
date conversion | Definition: public today:any=new Date() Use: {{today | date : 'yyyy-MM-dd HH-mm-ss'}} |
case conversion | Convert to uppercase: {{data1 | uppercase}} Convert to lowercase: {{data1 | lowercase}} |
number of decimal places | Format: Minimum number of integers. Minimum number of decimal places - maximum number of integers {{data2 | number:1.2-4}} |
Object Serialization | {{ {name:’jennifer’}| json}} |
String Interception | {{ ‘jennifer’|slice:0:3}} |
duct chain | {{‘jennifer’ | slice:0:3 | uppercase}} |
form (document)
Form type | byword | (for) instance |
input box | text | <input type=’text’ /> |
single election | radio | <input type='radio' value="male" name="sex" [(ngModel)]=""><label for='sex1'>male</label> <input type='radio' value="female" name="sex" [(ngModel)]=""><label for='sex1'>female</label> ngModle Bind Value value, when ngModel value and value value are the same, default is selected |
multiple choice | checkbox | <span *ngFor=’item of ’> <input type=’checkbox’ [(ngModel)]=’’ /> </span> The bidirectional binding is the value of check, which is true if it is checked |
drop-down list | select option |
<select name=’’ [(ngModel)]=’item’> <option [value]=’item’ *ngFor=’item of ’>{{item}}</option> </select> The two-way binding in Select is the value of the selected option. |
P6 (search records and todolist)
exports |
increase | remove | |
Search Cache | <input type=”text” [(ngModel)]=”keyword”/> <button (click)=”zengjia()”></button> <ul> <li *ngFor=”let item of arr; let key=index”>{{item}} <button (click)=”delete(key)”>removing</button></li> </ul> |
public arr:any[]=[]; public keyword:any; zengjia(){//Detect if same value exists if(()==-1){ () } } |
delete(key){ (key,1) } |
Todolist | |||
P7 data cache
service | root module | assemblies | ||||||
1.1 Creating services ng g service services/storage |
2.1 Introducing servicesimport {StorageService} from '. /services/'; | 3.1 Introducing services in components import {StorageService} from '../../services/'; |
||||||
1.2 Content in the service class set(key:any,value:any){ (key,(value)); } //from localstorage get(key:any){ return ((key)) } //remove from localstorage remove(key:any){ (key) } |
2.2 Registration @NgModule({ providers: [StorageService], }) |
3.2Registering in the componentconstructor(public storage:StorageService) { } 3.3 Using Methods from Service Classes in Components ('todolist',); ngOnInit() { var localList=('todolist'); =localList; } |
Dom operation
Get Document object.
import { DOCUMENT } from '@angular/common';
constructor(@Inject(DOCUMENT) private doc: Document) { }
P8ViewChild for Dom operations and component method calls
html:<div #wySlide></div> //
ts:
In the class {
private sliderDom: HTMLDivElement; //3. Type declarations
@ViewChild('wySlider', { static: true }) private wySlider: ElementRef; //2. Get ElementRef
ngOnInit(){
= ; //4. Get Dom
}}
P9 Parent-child component communication
communication method | Content in parent component | Content in subcomponents |
The child gets the parent's data @Input | public msgFromFather:any="I am the value passed from the parent component to the child component" <app-header [childMsg]=”msgFromFather”></app-header> |
import {Import} from ‘@angular/core’; @imprrt() childMsg:any; getMsg(){ () } |
The child executes the parent method @Input | funFromFather(){alert("Parent component method")} <app-header [run]=”funFromFather”></app-header> |
import {Import} from ‘@angular/core’; @Input run:any getRun(){ () } |
The child gets the entire parent component | public msg:any="Home" <app-header [home]=”this”></app-header> |
import {Input} from ‘@angular/core’ @Input home:any; getFatherMag(){ alert() } |
Parent gets child data/method @ViewChild | <app-header #header></app-header> import {ViewChild} from ‘@angular/core’ @ViewChild(“header”) box2 getChildMsg(){ return this.; } getChildFunc(){ return () } |
public msg:any="Subcomponent data" run(){alert("Subcomponent method")} |
Child triggers parent method and passes value (parent passively gets child data) | <app-header (outer)=”runParent($event)”></app-header> runParent(e){alert(outer)} |
<button (click)="setParent('incoming value')"></button> import {Output,EventEmitter} from ‘@angular/core’ @Output() private outer=new EventEmitter<string>(); //instantiated setParent(data){(data)} |
P10 Life Cycle
Asynchronous, Responsive
asynchronous programming method | Service content (RequestService) | component | account for |
callback function | getCallbackData(cb){ setTimeout(() => { var username = "jennifer"; cb(username); },1000); } |
construct(p){public request:RequestService} ngOnInit(){ ( (data) => {(data)} ) } |
The cb function is passed in as an argument to getCallbackData and then called by the asynchronous function setTimeOut Callback Functions: Passing a function as an argument to another function |
Promise | getPromiseData(){ return new Promise((resolve,reject) => { setTimeout(() => { var username = "jennifer"; resolve(username); },1000); }) } |
construct(p){public request:RequestService} ngOnInit(){ ().then( (data) => {(data)} ) } |
The asynchronous function setTimeOut in getPromiseData calls the resolve function after successful execution. () sets the contents of resolve() and reject(). |
Rxjs | import {Observable} from 'rxjs'; getRxjsData(){ let steam = new Obervable(observer =>{ setTimeout(() => { var username = "jennifer"; (username); ("Failure") },1000); }) }
|
construct(p){public request:RequestService} ngOnInit(){ var rxjs = (); ( (data) => {(data)} ) } |
subscript() setting |
Rxjs Unsubscribe | import {Observable} from 'rxjs'; getRxjsData(){ let steam = new Obervable(observer =>{ setTimeout(() => { var username = "jennifer"; (username); ("Failure") },3000); }) } |
construct(p){public request:RequestService} ngOnInit(){ var rxjs = (); var d = ( (data) => {(data)} ) setTimeOut(() => {()},1000) } |
|
Rxjs Multiple Executions | import {Observable} from 'rxjs'; getRxjsData(){ let steam = new Obervable(observer =>{ setInterval(() => { var username = "jennifer"; (username); ("Failure") },1000); }) } |
construct(p){public request:RequestService} ngOnInit(){ var rxjs = (); ( (data) => {(data)} ) } |
P12 requesting data
way (of life) | root module | assembly | Make a request in the component |
get | import {HttpClientModule} from ‘@angular/common/http’; | import {HttpClient} from '@angular/common/http'; (get request) import
constructor(public http:HttpClient){} |
var api=http://xxx; (api).subscribe(response => {(response); }); |
post | import {HttpClientModule} from ‘@angular/common/http’; | constructor(public http:HttpClient){} | const httpOptions = { headers:new HttpHeaders({‘Content-type’:’application/json’}) } var api=http://xxx/doLogin; (api,{username: "ZhangSan", age: "20"},httpOptions).subscribe( response => {(response)}; ); |
jsonp | import {HttpClientModule, httpClientJsonpModule} from ‘@angular/common/http’; | import {HttpClient} from ‘@angular/common/http’; constructor(public http:HttpClient){} |
var api=http://xxx/doLogin; (api,’callback’).subscribe(response =>{(response)}) |
methodologies | element | move | ||
axios | Using axios in Service HttpService | 1.1 Installation cnpm install axios --save |
1.2 New services ng g service services/httpservice Introducing axios in services import axios from ‘axios’ |
1.3 Using axios in service classes axiosGet(api){ return new Promise((resolve,reject) => { (api) .then(function(response){ resolve(response); }) }) } |
root module | 2.1 Introduction of service classes import {HttpService} from ‘./services/’; |
2.2 Registration @NgModule({ providers:[ HttpService], }) |
||
assembly | 3.1 Introduction of service classes import {HttpService} from ‘../../services/’; |
3.2 Instantiation constructor(public httpService: HttpService,){} |
3.3 Sending requests var api=http://xxx/doLogin; this. httpService. axiosGet(api).then((data) => { (data) }) |
P13 Routing
Configuration Rationale
The root routing module consists of the introduced components | Configuring Routes in the Root Routing Module | Using Routing |
import {HomeComponent} from ‘./home/’; import {newsComponent} from ‘./news/’; import {newsContentComponent} from ‘./newsContent/’; |
const routes:Routes = [ {path:’home’,component:HomeComponent}, { path:'news',component: newsComponent },//static route { path:'newsContent/:aid',component: newsContentComponent },// dynamic routing {path:'**',redirectTo:'home'} //default route
] |
<h1> <a [routerLink]=”[’/home’]”> Home</a> <a [routerLink]="['/news']"> news</a> </h1> <router-outlet></router-outlet> |
Routing passes (component switching + passes)
Components for passing out data | Acceptance Data Component | ||
get passes a value | Introducing Components import {HomeComponent} from ‘./home/’; import {newsComponent} from ‘./news/’; import {newsContentComponent} from ‘./newsContent/’; Routing configuration (static) const routes:Routes = [ {path:’home’,component:HomeComponent}, { path:’news’,component: newsComponent }, { path:’newsContent’,component: newsContentComponent }, {path:'**',redirectTo:'home'} //default route ] |
Passing values via queryParams <li *ngFor=”let item of list;let key =index”> <a [routerLink]=”[‘/newsContent’]” [queryParams]=”{aid:key}”>{{item}}</a> </li> |
Introducing ActivityRoute import {ActivatedRoute} from ‘@angular/router’; herald constructor(public route: ActivatedRoute){} Getting data ngOnInit(){ ((data) => { (data) }) } |
Dynamic Routing Passing | Introduction of components (as above) Routing configuration (dynamic) const routes:Routes = [ {path:'home',component:HomeComponent}, //normal route { path:'news',component: newsComponent }, // normal route { path:’newsContent/:aid',component: newsContentComponent }, // dynamic routing path:’**’,redirectTo:’home’} ] |
<li *ngFor=”let item of list;let key =index”> <a [routerLink]=”[‘/newsContent/’,key]”>{{item}}</a> </li> |
Introducing ActivityRoute import {ActivatedRoute} from ‘@angular/router’; herald constructor(public route:ActivitedRoute){} Getting data ngOnInit(){ ((data) => {data}) } |
Routing jumps (page jumps + passes)
methodologies | Pre-Jump Page | Receive Data Page |
Route getPass jsjump | trigger a jump <button (click)=” goNewsContent()”></button> |
Accepting data component newsContent introduces ActivityRoute and declares the import {ActivatedRoute} from ‘@angular/router’; constructor(public route: ActivatedRoute){} ngOnInit(){ ((data) => { (data) }) |
Introducing NavigationExtras import{Router, NavigationExtras} from ‘@angular/router’ Initialization in construct constructor(public router:Router){} Performs a jump, passing parameters with NavigationExtras configuration goNewsContent(){ //Definition data let msg: NavigationExtras = { queryParams:{‘userId’:’123’}, fragment:’anchor’ }; ([‘/news’], msg) } | ||
Dynamic routing jsjump | trigger a jump <button (click)="goNewsContent()"> js route jump (dynamic routing)<button> <button (click)="goHome ()">js route jump (normal route)<button> |
Components that receive data import {ActivatedRoute} from ‘@angular/router’; constructor(public route:ActivitedRoute){} ngOnInit(){ ((data) => {data}) } |
pull into import {Router} from ‘@angular/router’; initialization constructor(public router:Router){} navigate goNewsContent(){ ([‘/newsContent/’ ,’1234’]) } goHome(){ ([‘/Home’]) } |
P15 Nested routing (parent-child routing)
Scenario: there are parent and child components on the page, and different child components are loaded when clicking on them
Root Routing Module Configuring Routes | Parent component home | |
Create subcomponent news of home ng g component component components/home/news Introducing components (indentation) import {HomeComponent} from ‘./home/’; import {newsComponent} from ‘./news/’; Configuring Nested Routes const routes:Routes = [ {path:’home’,component:HomeComponent children:[ { path:’news’,component: newsComponent }, {path:'**',redirectTo:'news'} //loaded by default ] ] |
<a [routerLink]="['/home/welcome']"> load news component </a> <a [routerLink]="['/home/welcome']"> load notification component </a> <div> <router-outlet></router-outlet> </div> |
|
- Creating subcomponents of home
ng g component component components/home/welcome