1. NPM install angular-cli NPM i-g@angular /cli

Create your own project

ng new myAn

MyAn is our project name.

Angular component structure

import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']})export class AppComponent {
  title = 'myAn';
}Copy the code

Components generated

Get the component decorator from the Angular main module

import { Component } from '@angular/core';

Invoke the Component decorator definition, passing in Component source data as JSON @Component(json)

Selectore :string Component label name
call

TemlateUrl :string Path of the COMPONENT’S HTML template

StyleUrls :Array

Array of component CSS file paths

Where you define component controllers, logic code

export class AppComponent{}

Modular component

import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from'@angular/core';
import { AppComponent } from './app.component';
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }Copy the code

Introduce the module generator @NgModule

import { NgModule } from '@angular/core';

Json argument to the module generator

Declarations: Array data source for components and pipes of a composite module

Imports: Modules module dependency

Providers: Services provided by the Array module

Bootstrap: indicates the main component of the Array module

Create component command

Ng g Component Component name

External incoming value properties

The import@input core module is required

import {Input} from "@angular/core"

exportClass Componet {// declare @input props:[]; // Complete}Copy the code

External value transfer to component labels

< Componet [props] = ",1,3 [0] "> < / Componet >

Cycle instruction

*ngFor="let a in Array; let i in index "

A: Proxy entry

Index: an index

Attribute binding directives []

The binding class

[class. NewClass] or [ngClass] = bloore = {' a ': true, "bb" : false,' c ': true}

The binding style

[style. The font and size] = '24 px or [ngStyle] = {' the font - size:' 24 px ', 'color' : a > 10? 'red':'#fff' }


Angular routing System

Route objects

Routes:Array

Route configuration item

Routing view view tag

Router A Router object that can navigate to a specified route by calling its navigate() and navigateByUrl() methods

Router.navigate(Array

) to jump a route to the specified route [‘/’]

RouterLink: string Attributes labeled as route navigation

ActivatedRouter Object activated by the current route. Current route address and route parameters

Route configuration item parameter Routes

Routes:Array<json>

json: {path: '',component : center}

Path: indicates the route path without/and wildcard **

Component: Object Component object

The current route activates the object property and method ActivatedRouter

Proto. queryParams[id] Get parameter object =? id=10

Proto. params[id] Parameter of the current route activation object = A /: ID

Proto.data [index]. Id Active route data = [path: “, Component :com,data:[{id: ABC}]]

Redirection Routes redirectTo and pathMatch

{path:'', redirectTo:'/home',pathMatch:'full'}

RedirectTo :string Route address redirected to

PathMatch: Full Specifies whether to enable precise mode

Auxiliary routing

HTML placeholder structure:

// Route outlet <router-outlet></router-outlet> // Secondary route outlet"aux"
<router-outlet></router-oulet name='aux'>Copy the code

Route configuration:

routes=[
    {path:' ', Component :center},// Main route display {path:'auxVivwe',component:auxViwe,outlet:'aux'}// Secondary route display {path:'abcd',component:abcd,outlet:'aux'}// Secondary route display]Copy the code

Route navigation:

The primary route is /, and the secondary route redirects to auxVivwe <a [routerLink]="['/',{outlet:'aux','auxVivwe'}]">1</a>
Copy the code

Routing guard

CanActivate:fun is called to handle routing to a route. This method returns true to allow the route to enter and false to block the route.

CanDeactivate:fun handles the current route exit status call,

Resolve:fun is called before routing activation data

Inject the route guard to the route

{path: ‘/ home’, component: a, CanActivate: [ABC instance.]}

Route data acquisition function

Object. Subscribe (backFuntion) Calls the callback method immediately if the object data changes

Object.snapshot. object Obtains a data snapshot

Dependency injection, inversion of control

Injector:

constructor(prod:prod){}

Provider:

Providers :[{provider:’prod’,useClass:prod}

Providers :[{provider:’prod’,useFactory ()=>{return 1},deps:[loge]}] Provides factory method values

Providers :[{provider:’prod’,useValue:false}] Provides a value

Configuration parameters

The provider: signature string

UseClass: instance provided by the class

UseFactory :function returns a class or value from a method. The factory method is called only once when a service is needed. The value is persisted and returned directly for subsequent use

Deps :Array

intermediate provider for factory methods that provide services that are otherwise looked up from @ngModule or @ Component

Providers can be declared in @ngModuls() or @Component

Data binding

{{init}}~

//.classname

//.aa.bb.cc

//.bb

9. Style binding, josn expression

<div [ngStyle]={'font-0size':a? '12px':'30px','color':a? 'red':'green'}>

Piping (filter)

Filter the value and return it

As written in the VUE {{value | fun}}

Angular built-in pipes

Date :’ YYYY-MM-DD ‘

Convert to all uppercase

Convert to lowercase lowercase

Number :’2.2-2′

A custom pipe needs to be initialized in declarations

Create a custom pipe command line ng g pipe /piper/modele/


Component to component communication

Parent-child component communication

Father by value

@Input()
a:string;
<app-e  [a]='hello'></app-e>Copy the code

The child emits the event property and the parent receives the event trigger: EvnetEmitter

// Parent component template <div> <app-son (close)="setClose()"> </app-son>
</div>

exprot class app{
    setClose(){
        console.log('Child component to close pull')}}Copy the code

// Child <inputtype="button" (click)="postClose"< span style = "box-sizing: border-box! Important; word-wrap: break-word! Important;"'close')
    emit:EventEmitter<any>=new EventEmitter()

    postClose(){// emit this.emit. Emit ()}}Copy the code

@Output('close')
emit:EventEmitter<any>=new EventEmitter()
Copy the code

The emitted event is called CLOSE.

EventEmitter is angalur’s event firing object

The parent component calls the child’s method @viewChild ();

@ViewChild('child') child1:component this.child1.get(); // Invoke the child component's methodsCopy the code


Component lifecycle hooks

hook

Use and Timing

ngOnChanges()

Responds when Angular (re) sets the data binding input property. This method accepts SimpleChanges objects for the current and previous property values

Called when the value of the bound input property changes, the first call must occur before ngOnInit().

ngOnInit()

Initialize the directive/component after Angular first displays the data binding and set directive/component input properties.

Called after the first round of ngOnChanges(), only once.

ngDoCheck()

Detect, and react to changes that Angular can’t or won’t detect itself.

Called during every Angular change detection cycle, after ngOnChanges() and ngOnInit().

ngAfterContentInit()

Called after the content is projected into the component.

Called after the first ngDoCheck(), only once.

ngAfterContentChecked()

Called each time change detection of the projected component content is completed.

NgAfterContentInit () and after each ngDoCheck()

ngAfterViewInit()

Called after initializing the component view and its child views.

Called after ngAfterContentChecked() the first time, only once.

ngAfterViewChecked()

Called every time change detection is done for component views and child views.

NgAfterViewInit () and ngAfterContentChecked() each time.

ngOnDestroy()

Called and cleaned every time Angular destroys a directive/component. Here, unsubscribe observables and detach event handlers to prevent memory leaks.

Called before Angular destroys the directive/component.

Customize projection content to ng-centent components

<div> </ng-centent> </ng-centent> </div> // Component2 call incoming projection < app-Component1 >< h1>123456, I am a projection in </h1> </ app-Component1 >Copy the code

The Angalur form handles ngFrom

In Angalur, the ngFrom directive is automatically added to the FROM form to automatically process all form data bound to the ngModule directive

All form data can be accessed through myFrom when the ngFrom directive is added to the form

NgSubmit Anglular uses the ngSubmit event instead of the native Submit event

NgModuleGroup IS a subset of form data objects.

Reactive form reactiveFromsModule