Home  >  Article  >  Web Front-end  >  An in-depth analysis of directives, pipes and services in Angular

An in-depth analysis of directives, pipes and services in Angular

青灯夜游
青灯夜游forward
2021-09-18 10:58:132149browse

What are instructions, pipes, and services in Angular? The following article will take you through the instructions, pipelines and services in Angular. I hope it will be helpful to you!

An in-depth analysis of directives, pipes and services in Angular

1. DirectiveDirective

Directive is the operation provided by AngularDOM path. Instructions are divided into attribute instructions and structure instructions. [Related tutorial recommendation: "angular tutorial"]

Attribute instructions: Modify the appearance or behavior of existing elements and use [] packages.

Structure instructions: add and delete DOM nodes to modify the layout, use * as the instruction prefix

##1.1 Built-in instructions

1.1.1 *ngIf

Rendering based on conditions

DOM Node or remove DOM Node

<div *ngIf="data.length == 0">没有更多数据</div>
<div *ngIf="data.length > 0; then dataList else noData"></div>
<ng-template #dataList>课程列表</ng-template>
<ng-template #noData>没有更多数据</ng-template>

1.1.2 [hidden]

Display according to conditions

DOM node or hiddenDOM node(display)

<div [hidden]="data.length === 0">没有更多数据</div>

1.1.3 *ngFor

Traverse data to generate HTML structure

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

list: List[] = [
  { id: 1, name: "张三", age: 20 },
  { id: 2, name: "李四", age: 30 }
]
<!--  
    i: 索引
    isEven: 是否为偶数行
    isOdd: 是否为奇数行
    isFirst: 是否是第一项
    isLast: 是否是最后一项
-->
<li
    *ngFor="
      let item of list; 
      let i = index;
      let isEven = even;
      let isOdd = odd;
      let isFirst = first;
      let isLast = last;
    "
></li>
<li *ngFor="let item of list; trackBy: identify"></li>
identify(index, item){
  return item.id; 
}

1.2 Custom instructions

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

<div [appHover]="{ bgColor: &#39;skyblue&#39; }">Hello Angular</div>

  • Create custom instructions

  • $ ng g d appHover
    # 全称 ng generate directive
    import { AfterViewInit, Directive, ElementRef, HostListener, Input } from "@angular/core"
    
    // 接收参的数类型
    interface Options {
      bgColor?: string
    }
    
    @Directive({
      selector: "[appHover]"
    })
    export class HoverDirective implements AfterViewInit {
      // 接收参数
      @Input("appHover") appHover: Options = {}
      // 要操作的 DOM 节点
      element: HTMLElement
      // 获取要操作的 DOM 节点
      constructor(private elementRef: ElementRef) {
        this.element = this.elementRef.nativeElement
      }
      // 组件模板初始完成后设置元素的背景颜色
      ngAfterViewInit() {
        this.element.style.backgroundColor = this.appHover.bgColor || "skyblue"
      }
      // 为元素添加鼠标移入事件
      @HostListener("mouseenter") enter() {
        this.element.style.backgroundColor = "pink"
      }
      // 为元素添加鼠标移出事件
      @HostListener("mouseleave") leave() {
        this.element.style.backgroundColor = "skyblue"
      }
    }

2. PipelinePipe

#The role of the pipe is to format component template data.

2.1 Built-in pipeline

  • ##date

    Date formatting

  • currency

    Currency formatting

  • uppercase

    Convert to uppercase

  • lowercase

    Convert to lower case

  • json

    Formatjson Data

    <p>{{ date | date: "yyyy-MM-dd" }}</p>

2.2 Custom pipelineRequirement: The specified string cannot exceed the specified length

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

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

3. Service

Service

3.1 Create service

$ ng g s services/TestService --skip-tests
import { Injectable } from &#39;@angular/core&#39;;

@Injectable({
  providedIn: &#39;root&#39;
})
export class TestService { }
export class AppComponent {
  constructor (private testService: TestService) {}
}
3.2 Scope of service

Using services can easily achieve cross-module Share data across components, depending on the scope of the service.

    Register the service in the root injector, all modules use the same service instance object
  • import { Injectable } from &#39;@angular/core&#39;;
    
    @Injectable({
      providedIn: &#39;root&#39;
    })
    
    export class CarListService {
    }

  • Register the service at the module level, in this module All components use the same service instance object
  • import { Injectable } from &#39;@angular/core&#39;;
    import { CarModule } from &#39;./car.module&#39;;
    
    @Injectable({
      providedIn: CarModule,
    })
    
    export class CarListService {
    }
    import { CarListService } from &#39;./car-list.service&#39;;
    
    @NgModule({
      providers: [CarListService],
    })
    export class CarModule {
    }

  • To register services at the component level, the component and its subcomponents 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 ]
    })

Original address: https://juejin.cn/post/7008357218210807838


Author: Qianyi_0810

More programming related knowledge, Please visit:
programming video

! !

The above is the detailed content of An in-depth analysis of directives, pipes and services in Angular. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:掘金--浅忆_0810. If there is any infringement, please contact admin@php.cn delete