Home  >  Article  >  Web Front-end  >  Detailed explanation of how to create custom instructions in Angular

Detailed explanation of how to create custom instructions in Angular

青灯夜游
青灯夜游forward
2021-04-29 10:21:091630browse

This article will introduce to you how to customize the creation of instructions in Angular. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

Detailed explanation of how to create custom instructions in Angular

Introduction to directives

There are three types of directives in Angular:

  • Components have template instructions. Components inherit from instructions and just extend the class and UI-related attributes.

  • Attribute-type directives are directives that change the behavior and appearance of DOM elements, components, or other directives. For example, NgStyle, NgClass.

  • Structural directives are directives that change the DOM layout by adding or removing DOM elements. For example, NgIf, NgFor.

However, in actual development, according to business needs, we often expand the instructions of Angular components to facilitate business development. Let's take a look at how to create your own directive. [Related recommendations: "angular Tutorial"]

Create attribute-type instructions

In Angular, attribute-type instructions Creation requires at least a controller class with a @Directive decorator. This decorator specifies a selector name that identifies the attribute name associated with the directive. The controller class implements the functional behavior of the directive.

Next, we create a simple command to change the background color when the mouse hovers over the element; when the mouse moves away, the background color disappears; when the mouse is clicked, the font size becomes larger; when the mouse is released , the font returns to its original functionality.

Instruction implementation

Create the background-exed.directive.ts file and implement the following code:

import { Directive, HostListener, ElementRef, Renderer2, HostBinding } from '@angular/core';

@Directive({
  selector: '[appBackgroundExe]'
})
export class BackgroundExeDirective {

  @Input('appBackgroundExe')
  highLightColor: string;

  constructor(private elementRef: ElementRef, private renderer: Renderer2) {
    // 这种写法比较丑陋
    // this.elementRef.nativeElement.style.background = 'yellow';
    // 推荐这种写法, Renderer
    this.renderer.setStyle(this.elementRef.nativeElement, 'background', 'yellow');
  }

  @HostBinding('class.pressed')
  isPressed: boolean;

  @HostListener('mouseenter')
  onMouseEnter(): void {
   this.highLight(this.highLightColor);
  }

  @HostListener('mouseleave')
  onMouseLeave(): void {
    this.highLight(null);
  }

  @HostListener('mousedown')
  onMouseDown(): void {
    this.isPressed = true;
  }

  @HostListener('mouseup')
  onMouseUp(): void {
    this.isPressed = false;
  }

  private highLight(color: string): void {
    // this.elementRef.nativeElement.style.background = color;
    this.renderer.setStyle(this.elementRef.nativeElement, 'background', color);
  }

}

Among them, selector: '[appBackgroundExe]' Is the attribute name associated with the directive so that Angular can find the HTML code associated with this directive from the template when compiling. In the

constructor, instances of the ElementRef and Renderer2 modules are injected. Through ElementRef we can reference the DOM element identified by the instruction and perform related operations on it; and we can use the API provided by Renderer2 to perform related rendering operations on the element.

@HostListener and @HostBinding are property decorators. @HostListener is used to add event listening to the host element; and the element marked by the instruction is the host element. @HostBinding is used to dynamically set the attribute value of the host element.

Set font style

  • appliation.component.less
.pressed {
  font-size: 30px;
}

Use directives in templates

  • application.component.html
<div class="panel panel-primary">
  <div [appBackgroundExe]="&#39;red&#39;">鼠标移进,元素变成红色。鼠标移出,元素红色消失</div>
</div>

Create structural directive

structural directive Creation is similar to attribute-based instruction creation.

Instruction implementation

import { Directive, Input, TemplateRef, ViewContainerRef } from &#39;@angular/core&#39;;

@Directive({
    selector: &#39;[appIf]&#39;
})
export class IfDirective {

    constructor(
        private templateRef: TemplateRef<any>,
        private viewContainerRef: ViewContainerRef
    ) { }

    @Input(&#39;ifCreat&#39;) 
    set condition(condition: boolean) {
       if (condition) {
         this.viewContainerRef.createEmbeddedView(this.templateRef);
       } else {
         this.viewContainerRef.clear();
       }
    }
}

Among them, TemplateRef represents the embedded template template element through which embedded views can be created. ViewContainerRef represents a view container to which one or more views can be added, through which inline views or component views based on TemplateRef instances can be created and managed.

Using directives in templates

  • application.component.html
<div class="panel panel-primary">
  <div *ifCreate="&#39;true&#39;">hello</div>
</div>

Summary

This article mainly introduces how to customize the creation instructions in Angular. In actual development, we can flexibly create the instructions we want.

For more programming-related knowledge, please visit: Programming Teaching! !

The above is the detailed content of Detailed explanation of how to create custom instructions in Angular. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete