An in-depth analysis of directives, pipes and services in Angular
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!
1. DirectiveDirective
Directive is the operation provided by Angular
DOM
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
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]
DOM node or hidden
DOM node(
display)
<div [hidden]="data.length === 0">没有更多数据</div>
1.1.3 *ngFor
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: 'skyblue' }">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
Format
json
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 '@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] });
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) {}
}
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 { }
Copy after loginRegister the service at the module level, in this module All components use the same service instance objectimport { Injectable } from '@angular/core'; import { CarModule } from './car.module'; @Injectable({ providedIn: CarModule, }) export class CarListService { }
Copy after loginimport { CarListService } from './car-list.service'; @NgModule({ providers: [CarListService], }) export class CarModule { }
Copy after loginTo register services at the component level, the component and its subcomponents use the same service instance object- Original address: https://juejin.cn/post/7008357218210807838
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 after login
More programming related knowledge, Please visit:
Author: Qianyi_0810The 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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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 "Enter" key on the keyboard to open the chat window. 3. Enter the command format in the chat window: "/give[player name][item ID][item quantity]".

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.

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

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

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

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? 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

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.
