Home Web Front-end JS Tutorial Detailed explanation of the use of custom instructions in Angular17

Detailed explanation of the use of custom instructions in Angular17

Apr 13, 2018 am 11:47 AM
customize Detailed explanation

This time I will bring you a detailed explanation of the use of custom instructions in Angular17, and what are the precautions when using custom instructions in Angular17. The following is a practical case, let's take a look.

1 What is HTML

HTML document is a plain text file that contains HTML elements, CSS styles and JavaScriptcode; HTML elements are rendered by tags, and the browser will Each tag creates a DOM object with attributes, and the browser renders the content by rendering these DOM nodes. The content the user sees in the browser is the result of the browser rendering the DOM object.

2 Classification of instructions

˜Components, attribute directives, structural directives

 For specific knowledge points, please refer to "Angular2 Revealed"

3 refers to some constants commonly used in defining instructions

  3.1 Directive

Used to decorate the controller class to indicate that the controller class is a custom command controller class

  3.2 ElementRef

Used as a reference to a DOM object, dependency injection is performed through the constructor. Its instance represents the DOM object of the element marked with a custom instruction; each element marked with a custom instruction will automatically have an ElementRef object. as a reference to the element's DOM object (prerequisite: ElementRef is dependently injected in the controller of the custom directive)

  3.3 Render2

Instances of Render2 are used to operate DOM nodes, because Angular does not recommend directly operating DOM nodes; Render2 is only supported from Angular4, and previous versions used Render; each element marked with a custom instruction will have a Render2 instance to operate the DOM attribute of the element (prerequisite: Render2 is dependency injected in the controller of the custom directive)

  3.4 HostListener

Annotations used to decorate event triggering methods

4 Custom attribute directive

 A custom attribute directive requires a controller class decorated with @Directive decorator

import { Directive } from '@angular/core';
@Directive({
 selector: '[appDirectiveTest02]'
})
export class DirectiveTest02Directive {
 constructor() { }
}
Copy after login

4.1 Implement custom attribute instructions

    4.1.1 Create a custom attribute command control class

Tip 01: Create a module to specifically place custom instructions

ng g d directive/test/directive-test02 --spec=false --module=directive
Copy after login
#  ##    4.1.2 Dependency injection ElementRef  in the controller class

constructor(
 private el: ElementRef
 ) {}
Copy after login
     4.1.3 Change the background color of the DOM object corresponding to the element marked with a custom instruction through an ElementRef instance 

 ngOnInit() {
  this.el.nativeElement.style.backgroundColor = 'skyblue';
 }
Copy after login
     4.1.3 Specify exports       

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { DirectiveTest01Directive } from './test/directive-test01.directive';
import { SharedModule } from '../shared/shared.module';
import { DirectiveTest02Directive } from './test/directive-test02.directive';
@NgModule({
 imports: [
  CommonModule
 ],
 declarations: [
  DirectiveTest01Directive,
  DirectiveTest02Directive],
 exports: [
  DirectiveTest01Directive,
  DirectiveTest02Directive
 ]
})
export class DirectiveModule { }
Copy after login
in the custom instruction module    4.1.4 Import the custom instruction module into the module where the component that needs to use the specified instruction is located

Tip 01: Custom instructions are generally used multiple times, so the custom instruction module is generally imported into the shared module and exported from the shared module, so that other modules only need to import the shared module

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule } from '@angular/router';
import { 
 MdToolbarModule,
 MdSidenavModule,
 MdIconModule,
 MdButtonModule,
 MdCardModule,
 MdInputModule,
 MdRadioModule,
 MdRadioButton
 } from '@angular/material';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { DirectiveModule } from '../directive/directive.module'; 
@NgModule({
 imports: [
  CommonModule,
  RouterModule,
  FormsModule,
  ReactiveFormsModule,
  HttpModule,
  MdToolbarModule,
  MdSidenavModule,
  MdIconModule,
  MdButtonModule,
  MdCardModule,
  MdInputModule,
  DirectiveModule,
  MdRadioModule
 ],
 declarations: [],
 exports: [
  CommonModule,
  RouterModule,
  FormsModule,
  ReactiveFormsModule,
  HttpModule,
  MdToolbarModule,
  MdSidenavModule,
  MdIconModule,
  MdButtonModule,
  MdCardModule,
  MdInputModule,
  DirectiveModule,
  MdRadioButton
 ]
})
export class SharedModule { }
Copy after login
   4.1.5 Just use the selector corresponding to the custom component in the component

The selector of a custom directive is specified by the selector metadata of the @Directive decorator

Just mark the selector of the custom directive directly in the element.     4.1.6 Code Summary

<p class="panel panel-primary">
  <p class="panel panel-heading">实现自定义属性指令</p>
  <p class="panel-body">
    <button md-raised-button appDirectiveTest02>实现自定义指令的按钮</button>
    <br /><br />
    <button md-raised-button>未实现自定以指令的按钮</button>
  </p>
  <p class="panel-footer">2018-1-20 22:47:06</p>
</p>
Copy after login
4.2 Bind input attributes to custom attribute instructions

In the custom attribute instructions implemented in 4.1, the background color is hard-coded and cannot be changed. We can bind input attributes to the instructions to achieve data transfer, so as to achieve the purpose of dynamic change

     4.2.1 Add an input attribute myColor

import { Directive, ElementRef } from '@angular/core';
import { OnInit } from '../../../../node_modules/_@angular_core@4.4.6@@angular/core/src/metadata/lifecycle_hooks';
@Directive({
 selector: '[appDirectiveTest02]'
})
export class DirectiveTest02Directive implements OnInit {
 constructor(
 private el: ElementRef
 ) {}
 ngOnInit() {
 this.el.nativeElement.style.backgroundColor = 'skyblue';
 }
}
Copy after login
in the controller of the custom attribute directive      4.2.2 Assign a value to the myColor property in the component

      技巧01:在给输入属性赋值时,等号右边如果不是一个变量就需要用单引号括起来
View Code
    4.2.3 效果展示

    4.2.4 改进

      可以通过自定义属性指令的选择器来实现数据传输

      》利用自定义属性指令的选择器作为输入属性myColor输入属性的别名


      》在组件中直接利用自定义指令的选择器作为输入属性

View Code
      》 效果展示

  4.3 响应用户操作

    在自定义属性指令中通过监听DOM对象事件来进行一些操作

    4.2.1 引入 HostListener 注解并编写一个方法    

      技巧01:HostListener注解可以传入两个参数

        参数1 -> 需要监听的事件名称

        参数2 -> 事件触发时传递的方法

 @HostListener('click', ['$event'])
 onClick(ev: Event) {	
		  }	
Copy after login

    4.2.2 在方法中实现一些操作 

@HostListener('click', ['$event'])
 onClick(ev: Event) {
 if (this.el.nativeElement === ev.target) {
  if (this.el.nativeElement.style.backgroundColor === 'green') {
  this.el.nativeElement.style.backgroundColor = 'skyblue';
  } else {
  this.el.nativeElement.style.backgroundColor = 'green';
  }
 }
 // if (this.el.nativeElement.style.backgroundColor === 'yellow') {
 // this.el.nativeElement.style.backgroundColor = 'green';
 // } else {
 // this.el.nativeElement.style.backgroundColor = 'yellow';
 // }
 }
Copy after login

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

实现react服务器渲染的步奏详解

JS里EventLoop的使用详解

The above is the detailed content of Detailed explanation of the use of custom instructions in Angular17. 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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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 quickly set up a custom avatar in Netflix How to quickly set up a custom avatar in Netflix Feb 19, 2024 pm 06:33 PM

An avatar on Netflix is ​​a visual representation of your streaming identity. Users can go beyond the default avatar to express their personality. Continue reading this article to learn how to set a custom profile picture in the Netflix app. How to quickly set a custom avatar in Netflix In Netflix, there is no built-in feature to set a profile picture. However, you can do this by installing the Netflix extension on your browser. First, install a custom profile picture for the Netflix extension on your browser. You can buy it in the Chrome store. After installing the extension, open Netflix on your browser and log into your account. Navigate to your profile in the upper right corner and click

Detailed explanation of obtaining administrator rights in Win11 Detailed explanation of obtaining administrator rights in Win11 Mar 08, 2024 pm 03:06 PM

Windows operating system is one of the most popular operating systems in the world, and its new version Win11 has attracted much attention. In the Win11 system, obtaining administrator rights is an important operation. Administrator rights allow users to perform more operations and settings on the system. This article will introduce in detail how to obtain administrator permissions in Win11 system and how to effectively manage permissions. In the Win11 system, administrator rights are divided into two types: local administrator and domain administrator. A local administrator has full administrative rights to the local computer

How to customize shortcut key settings in Eclipse How to customize shortcut key settings in Eclipse Jan 28, 2024 am 10:01 AM

How to customize shortcut key settings in Eclipse? As a developer, mastering shortcut keys is one of the keys to improving efficiency when coding in Eclipse. As a powerful integrated development environment, Eclipse not only provides many default shortcut keys, but also allows users to customize them according to their own preferences. This article will introduce how to customize shortcut key settings in Eclipse and give specific code examples. Open Eclipse First, open Eclipse and enter

Detailed explanation of division operation in Oracle SQL Detailed explanation of division operation in Oracle SQL Mar 10, 2024 am 09:51 AM

Detailed explanation of division operation in OracleSQL In OracleSQL, division operation is a common and important mathematical operation, used to calculate the result of dividing two numbers. Division is often used in database queries, so understanding the division operation and its usage in OracleSQL is one of the essential skills for database developers. This article will discuss the relevant knowledge of division operations in OracleSQL in detail and provide specific code examples for readers' reference. 1. Division operation in OracleSQL

The operation process of edius custom screen layout The operation process of edius custom screen layout Mar 27, 2024 pm 06:50 PM

1. The picture below is the default screen layout of edius. The default EDIUS window layout is a horizontal layout. Therefore, in a single-monitor environment, many windows overlap and the preview window is in single-window mode. 2. You can enable [Dual Window Mode] through the [View] menu bar to make the preview window display the playback window and recording window at the same time. 3. You can restore the default screen layout through [View menu bar>Window Layout>General]. In addition, you can also customize the layout that suits you and save it as a commonly used screen layout: drag the window to a layout that suits you, then click [View > Window Layout > Save Current Layout > New], and in the pop-up [Save Current Layout] Layout] enter the layout name in the small window and click OK

Detailed explanation of the role and usage of PHP modulo operator Detailed explanation of the role and usage of PHP modulo operator Mar 19, 2024 pm 04:33 PM

The modulo operator (%) in PHP is used to obtain the remainder of the division of two numbers. In this article, we will discuss the role and usage of the modulo operator in detail, and provide specific code examples to help readers better understand. 1. The role of the modulo operator In mathematics, when we divide an integer by another integer, we get a quotient and a remainder. For example, when we divide 10 by 3, the quotient is 3 and the remainder is 1. The modulo operator is used to obtain this remainder. 2. Usage of the modulo operator In PHP, use the % symbol to represent the modulus

Detailed explanation of the linux system call system() function Detailed explanation of the linux system call system() function Feb 22, 2024 pm 08:21 PM

Detailed explanation of Linux system call system() function System call is a very important part of the Linux operating system. It provides a way to interact with the system kernel. Among them, the system() function is one of the commonly used system call functions. This article will introduce the use of the system() function in detail and provide corresponding code examples. Basic Concepts of System Calls System calls are a way for user programs to interact with the operating system kernel. User programs request the operating system by calling system call functions

How to customize x-axis and y-axis in excel? (How to customize excel axis scale) How to customize x-axis and y-axis in excel? (How to customize excel axis scale) Mar 14, 2024 pm 02:10 PM

In an excel table, sometimes you may need to insert coordinate axes to see the changing trend of the data more intuitively. Some friends still don’t know how to insert coordinate axes in the table. Next, I will share with you how to customize the coordinate axis scale in Excel. Coordinate axis insertion method: 1. In the excel interface, select the data. 2. In the insertion interface, click to insert a column chart or bar chart. 3. In the expanded interface, select the graphic type. 4. In the right-click interface of the table, click Select Data. 5. In the expanded interface, you can customize it.

See all articles