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

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

青灯夜游
Release: 2021-09-18 10:58:13
forward
2203 people have browsed it

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>
Copy after login
<div *ngIf="data.length > 0; then dataList else noData"></div>
<ng-template #dataList>课程列表</ng-template>
<ng-template #noData>没有更多数据</ng-template>
Copy after login

1.1.2 [hidden]

Display according to conditions

DOM node or hiddenDOM node(display)

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

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 }
]
Copy after login
<!--  
    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>
Copy after login
<li *ngFor="let item of list; trackBy: identify"></li>
Copy after login
identify(index, item){
  return item.id; 
}
Copy after login

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>
Copy after login

  • Create custom instructions

  • $ ng g d appHover
    # 全称 ng generate directive
    Copy after login
    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"
      }
    }
    Copy after login

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>
    Copy after login

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;;
    }
}
Copy after login
// app.module.ts
import { SummaryPipe } from &#39;./summary.pipe&#39;
@NgModule({
    declarations: [SummaryPipe] 
});
Copy after login

3. Service

Service

3.1 Create service

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

@Injectable({
  providedIn: &#39;root&#39;
})
export class TestService { }
Copy after login
export class AppComponent {
  constructor (private testService: TestService) {}
}
Copy after login
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 {
    }
    Copy after login

  • 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 {
    }
    Copy after login
    import { CarListService } from &#39;./car-list.service&#39;;
    
    @NgModule({
      providers: [CarListService],
    })
    export class CarModule {
    }
    Copy after login

  • To register services at the component level, the component and its subcomponents use the same service instance object
  • import { Component } from &#39;@angular/core&#39;;
    import { CarListService } from &#39;../car-list.service.ts&#39;
    
    @Component({
      selector:    &#39;app-car-list&#39;,
      templateUrl: &#39;./car-list.component.html&#39;,
      providers:  [ CarListService ]
    })
    Copy after login

    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!

Related labels:
source:掘金--浅忆_0810
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template