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:131987browse

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

没有更多数据
课程列表 没有更多数据

1.1.2 [hidden]

Display according to conditions

DOM node or hiddenDOM node(display)

没有更多数据

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 }
]

  • 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

    Hello Angular

    • 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

      {{ date | date: "yyyy-MM-dd" }}

    2.2 Custom pipelineRequirement: The specified 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) + '...';
        }
    }
    // app.module.ts
    import { SummaryPipe } from './summary.pipe'
    @NgModule({
        declarations: [SummaryPipe] 
    });

    3. Service

    Service

    3.1 Create service

    $ ng g s services/TestService --skip-tests
    import { Injectable } from '@angular/core';
    
    @Injectable({
      providedIn: 'root'
    })
    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 '@angular/core';
      
      @Injectable({
        providedIn: 'root'
      })
      
      export class CarListService {
      }

    • Register the service at the module level, in this module All components use the same service instance object
    • import { Injectable } from '@angular/core';
      import { CarModule } from './car.module';
      
      @Injectable({
        providedIn: CarModule,
      })
      
      export class CarListService {
      }
      import { CarListService } from './car-list.service';
      
      @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