Table of Contents
1. DirectiveDirective
2. PipelinePipe
Service
Using services can easily achieve cross-module Share data across components, depending on the scope of the service.
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

Sep 18, 2021 am 10:58 AM
angular instruction Serve pipeline

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to get items using commands in Terraria? -How to collect items in Terraria? How to get items using commands in Terraria? -How to collect items in Terraria? Mar 19, 2024 am 08:13 AM

How to get items using commands in Terraria? 1. What is the command to give items in Terraria? In the Terraria game, giving command to items is a very practical function. Through this command, players can directly obtain the items they need without having to fight monsters or teleport to a certain location. This can greatly save time, improve the efficiency of the game, and allow players to focus more on exploring and building the world. Overall, this feature makes the gaming experience smoother and more enjoyable. 2. How to use Terraria to give item commands 1. Open the game and enter the game interface. 2. Press the &quot;Enter&quot; key on the keyboard to open the chat window. 3. Enter the command format in the chat window: &quot;/give[player name][item ID][item quantity]&quot;.

Solution to Windows 10 Security Center service being disabled Solution to Windows 10 Security Center service being disabled Jul 16, 2023 pm 01:17 PM

The Security Center service is a built-in computer protection function in the win10 system, which can protect computer security in real time. However, some users encounter a situation where the Security Center service is disabled when booting the computer. What should they do? It's very simple. You can open the service panel, find the SecurityCenter item, then right-click to open its properties window, set the startup type to automatic, and then click Start to start the service again. What to do if the Win10 Security Center service is disabled: 1. Press "Win+R" to open the "Operation" window. 2. Then enter the "services.msc" command and press Enter. 3. Then find the "SecurityCenter" item in the right window and double-click it to open its properties window.

How to install Angular on Ubuntu 24.04 How to install Angular on Ubuntu 24.04 Mar 23, 2024 pm 12:20 PM

Angular.js is a freely accessible JavaScript platform for creating dynamic applications. It allows you to express various aspects of your application quickly and clearly by extending the syntax of HTML as a template language. Angular.js provides a range of tools to help you write, update and test your code. Additionally, it provides many features such as routing and form management. This guide will discuss how to install Angular on Ubuntu24. First, you need to install Node.js. Node.js is a JavaScript running environment based on the ChromeV8 engine that allows you to run JavaScript code on the server side. To be in Ub

How to use pipes to read and write files in Golang? How to use pipes to read and write files in Golang? Jun 04, 2024 am 10:22 AM

File reading and writing through pipes: Create a pipe to read data from the file and pass it through the pipe Receive the data from the pipe and process it Write the processed data to the file Use goroutines to perform these operations concurrently to improve performance

How to open Remote Desktop Connection Service using command How to open Remote Desktop Connection Service using command Dec 31, 2023 am 10:38 AM

Remote desktop connection has brought convenience to many users' daily lives. Some people want to use commands to connect remotely, which is more convenient to operate. So how to connect? Remote Desktop Connection Service can help you solve this problem by using a command to open it. How to set up the remote desktop connection command: Method 1. Connect remotely by running the command 1. Press "Win+R" to open "Run" and enter mstsc2, then click "Show Options" 3. Enter the IP address and click "Connect". 4. It will show that it is connecting. Method 2: Connect remotely through the command prompt 1. Press "Win+R" to open "Run" and enter cmd2. In the "Command Prompt" enter mstsc/v:192.168.1.250/console

How to enable audio service in win7 How to enable audio service in win7 Jul 10, 2023 pm 05:13 PM

Computers have many system services to support the application of various programs. If the computer has no sound and most audio services are not turned on after troubleshooting hardware problems, how do you enable audio services in win7? Many friends are confused, so for the question of how to enable the audio service in win7, the editor below will introduce how to enable the audio service in win7. How to enable audio service in win7. 1. Find the computer on the computer desktop under Windows 7 system, right-click and select the management option. 2. Find and open the service item under Services and Applications in the computer management interface that opens. Find WindowsAudio on the service interface on the right and double-click to open the modification. 4. Switch to the regular project and click Start to enable the function.

What is the correct way to restart a service in Linux? What is the correct way to restart a service in Linux? Mar 15, 2024 am 09:09 AM

What is the correct way to restart a service in Linux? When using a Linux system, we often encounter situations where we need to restart a certain service, but sometimes we may encounter some problems when restarting the service, such as the service not actually stopping or starting. Therefore, it is very important to master the correct way to restart services. In Linux, you can usually use the systemctl command to manage system services. The systemctl command is part of the systemd system manager

Angular components and their display properties: understanding non-block default values Angular components and their display properties: understanding non-block default values Mar 15, 2024 pm 04:51 PM

The default display behavior for components in the Angular framework is not for block-level elements. This design choice promotes encapsulation of component styles and encourages developers to consciously define how each component is displayed. By explicitly setting the CSS property display, the display of Angular components can be fully controlled to achieve the desired layout and responsiveness.

See all articles