您好,欢迎访问一九零五行业门户网

浅谈angular中的三种类型指令:组件型、结构型、属性型

本篇文章带大家了解一下angular中的指令,介绍一下组件型指令、结构型指令、属性型指令三种类型的指令,希望对大家有所帮助!
在 angular 中有三种类型的指令:
组件型指令 — 组件是特殊存在,拥有模板结构型指令 — 通过添加和移除 dom 元素改变 dom 布局的指令,常用的有:*ngif,*ngfor,ngswitch属性型指令 — 改变元素、组件或其它指令的外观和行为的指令,常用的有:ngclass,ngstyle【相关教程推荐:《angular教程》】
angular 指令——https://angular.cn/guide/built-in-directives
组件型指令
在查看angular源代码时,会看到如下
所以说组件是继承指令的,只是它比较特殊,有模版
同样,因为组件继承指令,在下面属性型和结构型指令的一系列操作,在组件中都是可以实现的
但是因为指令的目的是为了复用,在组件中这样操作是达不到这个目的,所以强烈不推荐这样去操作.
属性型指令
上面说道属性型指令是用来改变元素、组件或其它指令的外观和行为
那么我们如何打造属于自己的属性型指令呢?
首先,创建指令很像创建组件。
导入 directive 装饰器导入符号input、templateref 和 viewcontainerref,视指令类型与需求来选择给指令类添加装饰器。设置 css 属性选择器 ,以便在模板中标识出这个指令该应用于哪个元素。自定义属性型指令
1、创建属性型指令apphighlight指令:highlight.directive.ts
// 1、导入 directive 装饰器// 3、导入 elementref。elementref 的 nativeelement 属性会提供对宿主 dom 元素的直接访问权限import { directive, elementref } from '@angular/core';// 2、@directive() 装饰器的 selector 属性会指定指令的 css 属性选择器 [apphighlight]@directive({ selector: '[apphighlight]'})export class highlightdirective {// 4、构造函数中使用 elementref 来注入宿主 dom 元素的引用 constructor(el: elementref) { // 将对应元素的背景颜色设置为 黄色 el.nativeelement.style.backgroundcolor = 'yellow'; }}
与component和pipe一样,directive也需要在declarations数组中声明才能使用
2、宿主元素用法
<p apphighlight>highlight me!</p>
处理用户事件
下面指令的功能为:
能够接收2个参数,其中一个为另外一个的默认值
监听宿主元素的鼠标进入和离开事件,在进入时宿主背景颜色为上述传入的值
import { directive, elementref, hostlistener, input } from '@angular/core'; @directive({ //指定指令的属性型选择器 selector: '[apphighlight]'}) export class highlightdirective { @input('apphighlight') highlightcolor: string; @input() defaultcolor: string; //构造函数中使用 elementref 来注入宿主 dom 元素的引用 constructor(private el: elementref) { } //监听宿主元素 mousenter 事件 @hostlistener('mouseenter') onmouseenter() { this.highlight(this.highlightcolor || this.defaultcolor); } //监听宿主元素 mouseleave 事件 @hostlistener('mouseleave') onmouseleave() { this.highlight(null); } // 修改背景颜色 private highlight(color: string) { //elementref通过其 nativeelement 属性,提供直接访问宿主 dom 元素的能力。 this.el.nativeelement.style.backgroundcolor = color; }}
宿主元素用法
<p apphighlight="red" defaultcolor="black">宿主元素</p>
结构型指令
结构型指令的职责是 html 布局。 它们塑造或重塑 dom 的结构,这通常是通过添加、移除和操纵它们所附加到的宿主元素来实现的。
常见内置结构性指令:
ngif —— 从模板中创建或销毁子视图。ngfor —— 为列表中的每个条目重复渲染一个节点。ngswitch —— 一组在备用视图之间切换的指令。具体使用方法查看官网自定义结构性指令
其效果是:
如果条件是假值,并且 angular 以前尚未创建视图,则此 setter 会导致视图容器从模板创建出嵌入式视图。如果条件为真值,并且当前正显示着视图,则此 setter 会清除容器,这会导致销毁该视图。
1、创建指令ts文件:unless.directive.ts
// 1、导入 input、templateref 和 viewcontainerrefimport { directive, input, templateref, viewcontainerref } from '@angular/core';// 2、添加 directive 装饰器@directive({ selector: '[appunless]'})export class unlessdirective { private hasview = false; // 3、在指令的构造函数中将 templateref 和 viewcontainerref 注入成私有变量。 constructor( private templateref: templateref<any>, private viewcontainer: viewcontainerref ) { } // 4、添加一个带 setter 的 @input() 属性 appunless @input() set appunless(condition: boolean) { // 如果条件是假值,并且 angular 以前尚未创建视图,则此 setter 会导致视图容器从模板创建出嵌入式视图。 if (!condition && !this.hasview) { this.viewcontainer.createembeddedview(this.templateref); this.hasview = true; } else if (condition && this.hasview) { // 如果条件为真值,并且当前正显示着视图,则清除容器,这会导致销毁该视图。 this.viewcontainer.clear(); this.hasview = false; } }}
2、测试指令
<p *appunless="condition">show this sentence unless the condition is true.</p>
结构型指令(例如 *ngif)上的星号 * 语法是 angular 解释为较长形式的简写形式。 angular 将结构型指令前面的星号转换为围绕宿主元素及其后代的<ng-template>。
例如:*ngif
<div *ngif="hero" class="name">{{hero.name}}</div>
会被转换为
<ng-template [ngif]="hero"> <div class="name">{{hero.name}}</div></ng-template>
angular 不会创建真正的 <ng-template> 元素,只会将 <p> 和注释节点占位符渲染到 dom 中
自定义指令例详
下面的指令会去掉input输入框中的所有空格
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('触发了onchange', this.firstname) }}@directive({ selector: '[testdirective]', // host: { // 要传递传递事件参数,使用这种方法,不用的可以使用下面的 @hostlistener 方法 // '(keyup)': 'onkeyup($event)', // }})export class testdirective { constructor(public ngcontrol: ngcontrol) {} ngoninit() {} // onkeyup(event) { @hostlistener('keyup') onkeyup(event) { // console.log("event", event) // 事件参数 console.log(this.ngcontrol) console.log(this.ngcontrol.control) console.log(this.ngcontrol.control.value) if(/\s+/g.test(this.ngcontrol.control.value)) { // 只读属性,要通过 setvalue 修改 // this.ngcontrol.control.value = this.ngcontrol.control.value.replace(/\s+/g, '') this.ngcontrol.control.setvalue(this.ngcontrol.control.value.replace(/\s+/g, '')) } }}
使用:
<form action="" [formgroup] = 'profileform'> <label> first name: <input type="text" testdirective formcontrolname="firstname" [(ngmodel)] = "firstname" (ngmodelchange) = "onchange($event)"> </label> <label> last name: <input type="text" testdirective formcontrolname="lastname"> </label> <button type="submit" [disabled]="!profileform.valid">submit</button></form>
使用效果
上面的input的初始值为aa,在其中间输入空格字符,首先触发onchange事件,然后在指令触发keyup事件,改变了firstname的值,然后重新触发onchange事件,所以change事件一共触发两次。
更多编程相关知识,请访问:编程入门!!
以上就是浅谈angular中的三种类型指令:组件型、结构型、属性型的详细内容。
其它类似信息

推荐信息