Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the types of type instructions in angular

2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article introduces the relevant knowledge of "what are the type instructions in angular". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

This article takes you to understand the instructions in angular, and introduces three types of instructions: component instruction, structural instruction and attribute instruction. I hope it will be helpful to you!

There are three types of instructions in Angular:

Component instruction-the component is a special presence and has a template

Structural instructions-instructions to change the layout of a DOM by adding and removing DOM elements, commonly used are: * ngIf,*ngFor,ngSwitch

Attribute instruction-an instruction that changes the appearance and behavior of an element, component, or other instruction, commonly used: NgClass,NgStyle

Angular instruction-- https://angular.cn/guide/built-in-directives

Component-based instruction

When you look at the angular source code, you will see the following

So the component inherits instructions, but it is special and has templates.

Similarly, because the component inherits instructions, a series of operations in the following attribute and structural instructions can be implemented in the component

However, because the purpose of the instruction is to reuse, this operation in the component can not achieve this purpose, so this operation is not highly recommended.

Attribute instruction

It is said that attribute instructions are used to change the appearance and behavior of elements, components, or other instructions.

So how do we create our own attribute instructions?

First, creating an instruction is a lot like creating a component.

Import Directive decorator

Import symbols Input, TemplateRef and ViewContainerRef, depending on instruction type and requirement

Add a decorator to the instruction class.

Set the CSS property selector to identify the element to which this directive should be applied in the template.

Custom attribute instruction

1. Create attribute instruction appHighlight instruction: highlight.directive.ts

/ / 1. Import Directive decorator / / 3, import ElementRef. The nativeElement attribute of ElementRef provides direct access to the host DOM element import {Directive, ElementRef} from'@ angular/core' The selector attribute of the @ Directive () decorator specifies the CSS attribute selector of the instruction [appHighlight] @ Directive ({selector:'[appHighlight]'}) export class HighlightDirective {/ / 4, and the reference constructor (el: ElementRef) that injects the host DOM element using ElementRef in the constructor {/ / sets the background color of the corresponding element to yellow el.nativeElement.style.backgroundColor = 'yellow';}}

Like component and pipe, directive needs to be declared in the declarations array to use

2. Usage of host elements

Highlight me!

Handling user events

The functions of the following instructions are:

Can receive 2 parameters, one of which is the default value of the other

Listens for mouse entry and departure events of the host element, and when entering, the host background color is the value passed in above

Import {Directive, ElementRef, HostListener, Input} from'@ angular/core'; @ Directive (selector:'[appHighlight]'}) export class HighlightDirective {@ Input ('appHighlight') highlightColor: string; @ Input () defaultColor: string / / use ElementRef in the constructor to inject the reference constructor (private el: ElementRef) {} / / listen to the host element mousenter event @ HostListener ('mouseenter') onMouseEnter () {this.highlight (this.highlightColor | | this.defaultColor);} / listen to the host element mouseleave event @ HostListener (' mouseleave') onMouseLeave () {this.highlight (null) } / / modify background color private highlight (color: string) {/ / ElementRef provides direct access to host DOM elements through its nativeElement attribute. This.el.nativeElement.style.backgroundColor = color;}}

Host element usage

Host element

Structural instruction

The responsibility of structural directives is HTML layout. They shape or reshape the structure of DOM, usually by adding, removing, and manipulating the host elements to which they are attached.

Common built-in structural instructions:

NgIf-creates or destroys child views from the template.

NgFor-renders one node repeatedly for each entry in the list.

NgSwitch-A set of instructions to switch between alternate views. See the official website for specific usage.

Custom structural directive

The effect is:

If the condition is false and Angular has not previously created a view, this setter causes the view container to create an embedded view from the template.

If the condition is true and the view is currently displayed, this setter clears the container, which causes the view to be destroyed.

1. Create an instruction ts file: unless.directive.ts

/ / 1. Import Input, TemplateRef and ViewContainerRefimport {Directive, Input, TemplateRef, ViewContainerRef} from'@ angular/core';// 2, add the Directive decorator @ Directive ({selector:'[appUnless]'}) export class UnlessDirective {private hasView = false; / / 3, and inject TemplateRef and ViewContainerRef into the instruction constructor as private variables. Constructor (private templateRef: TemplateRef, private viewContainer: ViewContainerRef) {} / / 4, add a @ Input () attribute appUnless @ Input () set appUnless (condition: boolean) with setter {/ / if the condition is false and Angular has not previously created a view, this setter causes the view container to create an embedded view from the template. If (! condition & &! this.hasView) {this.viewContainer.createEmbeddedView (this.templateRef); this.hasView = true;} else if (condition & & this.hasView) {/ / if the condition is true and the view is currently displayed, the container is cleared, which causes the view to be destroyed. This.viewContainer.clear (); this.hasView = false;}

2. Test instruction

Show this sentence unless the condition is true.

The asterisk * syntax on structured instructions (for example, * ngIf) is an abbreviated form that Angular interprets as a longer form. Angular converts the asterisk in front of the structured instruction to the one that surrounds the host element and its descendants.

For example: * ngIf

{{hero.name}}

Will be converted to

{{hero.name}}

Angular does not create real elements, only sets the

And comment node placeholders are rendered to DOM

Custom instruction example

The following instructions remove all spaces in the input input box

Import {Component, Directive, HostListener} from'@ angular/core'import {hostElement} from'@ angular/core/src/render3/instructions';import {FormGroup, FormControl, Validators, NgControl} from'@ angular/forms'@Component ({selector: "app-test", templateUrl: ". / test.component.html", / / declarations: [TestDirective]}) export class TestComponent {constructor () {} ngOninit () {} firstName ='; lastName ='' ProfileForm = new FormGroup ({firstName: new FormControl ('aa', [Validators.required,Validators.pattern (' [a-zA-Z0-9] *')]), lastName: new FormControl ('', Validators.required),}) Onchange (event) {console.log ('triggered onchange', this.firstName)} @ Directive ({selector:' [testDirective]', / / host: {/ / to pass event parameters, use this method If you don't need it, you can use the following @ HostListener method / /'(keyup)': 'onkeyup ($event)', / /}}) export class TestDirective {constructor (public ngControl: NgControl) {} ngOnInit () {} / / onkeyup (event) {@ HostListener ('keyup') onkeyup (event) {/ / console.log ("event") Event) / / event parameter console.log (this.ngControl) console.log (this.ngControl.control) console.log (this.ngControl.control.value) if (/\ s+/g.test (this.ngControl.control.value)) {/ / read-only attribute To modify / / this.ngControl.control.value = this.ngControl.control.value.replace (/\ spepper _ g,'') this.ngControl.control.setValue (this.ngControl.control.value.replace (/\ s _ scratch _ g,'')} via setValue

Use:

First Name: Last Name: Submit

The initial value of the above input is aa, enter a space character between it, first trigger the onchange event, then trigger the keyup event in the instruction, change the value of firstName, and then trigger the onchange event again, so the change event is triggered twice.

This is the end of the content of "what are the type instructions in angular?" Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report