Instructions 1.Directive

Directives are Angular’s way of manipulating the DOM. Instructions are divided into attribute instructions and structural instructions.

Attribute directives: Modify the appearance or behavior of an existing element, wrapped in [].

Structural directives: Add and remove DOM nodes to modify the layout, prefixed with *

1.1 Built-in Instructions

1.1.1 *ngIf

Render or remove DOM nodes based on conditions

<div *ngIf="data.length == 0">No more data</div>
Copy the code
<div *ngIf="data.length > 0; then dataList else noData"></div>
<ng-template #dataList>Course list</ng-template>
<ng-template #noData>No more data</ng-template>
Copy the code
1.1.2 [hidden]

Show or hide DOM nodes based on conditions (display)

<div [hidden] ="data.length === 0">No more data</div>
Copy the code
1.1.3 *ngFor

Iterate over the data to generate HTML structures

interface List {
  id: number
  name: string
  age: number
}

list: List[] = [
  { id: 1.name: "Zhang".age: 20 },
  { id: 2.name: "Bill".age: 30}]Copy the code
<! -- I: index isEven: whether it is an even row isOdd: whether it is an odd row isFirst: whether it is the first item isLast: whether it is the last item -->
<li
    *ngFor=" let item of list; let i = index; let isEven = even; let isOdd = odd; let isFirst = first; let isLast = last; "
></li>
Copy the code
<li *ngFor="let item of list; trackBy: identify"></li>
Copy the code
identify(index, item){
  return item.id; 
}
Copy the code

1.2 Custom Instructions

Requirement: Set the default background color for the element, the background color when the mouse moves in and the background color when the mouse moves out

<div [appHover] ="{ bgColor: 'skyblue' }">Hello Angular</div>
Copy the code
  1. Create custom directives
$ ng g d appHover
Ng generate directive
Copy the code
import { AfterViewInit, Directive, ElementRef, HostListener, Input } from "@angular/core"

// The number type of the received parameter
interfaceOptions { bgColor? :string
}

@Directive({
  selector: "[appHover]"
})
export class HoverDirective implements AfterViewInit {
  // Receive parameters
  @Input("appHover") appHover: Options = {}
  // The DOM node to operate on
  element: HTMLElement
  // Get the DOM node to operate on
  constructor(private elementRef: ElementRef) {
    this.element = this.elementRef.nativeElement
  }
  // Set the background color of the element after the component template is initialized
  ngAfterViewInit() {
    this.element.style.backgroundColor = this.appHover.bgColor || "skyblue"
  }
  // Add a mouse-over event to the element
  @HostListener("mouseenter") enter() {
    this.element.style.backgroundColor = "pink"
  }
  // Add a mouse out event to the element
  @HostListener("mouseleave") leave() {
    this.element.style.backgroundColor = "skyblue"}}Copy the code

2. The pipePipe

Pipes are used to format component template data.

2.1 Built-in Pipes

  1. dateDate formatting
  2. currencyCurrency formatting
  3. uppercaseTurn the capital
  4. lowercaseTurn to lowercase
  5. jsonformattingjsondata
<p>{{ date | date: "yyyy-MM-dd" }}</p>
Copy the code

2.2 User-defined Pipes

Requirement: Specify that the string cannot exceed the specified length

// summary.pipe.ts
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
   name: 'summary' 
});
export class SummaryPipe implements PipeTransform {
    transform (value: string, limit? :number) {
        if(! value)return null;
        let actualLimit = (limit) ? limit : 10;
        return value.substr(0, actualLimit) + '... '; }}Copy the code
// app.module.ts
import { SummaryPipe } from './summary.pipe'
@NgModule({
    declarations: [SummaryPipe] 
});
Copy the code

3. The serviceService

3.1 Creating a Service

$ ng g s services/TestService --skip-tests
Copy the code
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class TestService {}Copy the code
export class AppComponent {
  constructor (private testService: TestService) {}}Copy the code

3.2 Scope of services

Using services, you can easily share data across modules and components, depending on the scope of the service.

  1. The service is registered in the root injector and all modules use the same service instance object

    import { Injectable } from '@angular/core';
    
    @Injectable({
      providedIn: 'root'
    })
    
    export class CarListService {}Copy the code
  2. Register a service at the module level, where all components use the same service instance object

    import { Injectable } from '@angular/core';
    import { CarModule } from './car.module';
    
    @Injectable({
      providedIn: CarModule,
    })
    
    export class CarListService {}Copy the code
    import { CarListService } from './car-list.service';
    
    @NgModule({
      providers: [CarListService],
    })
    export class CarModule {}Copy the code
  3. A service is registered at the component level, and the component and its children use the same service instance object

    import { Component } from '@angular/core';
    import { CarListService } from '.. /car-list.service.ts'
    
    @Component({
      selector:    'app-car-list'.templateUrl: './car-list.component.html'.providers:  [ CarListService ]
    })
    Copy the code