指令Directive
- 指令是为Angular应用程序中的元素添加额外行为的类,使用Angular的内置指令,你可以管理表单、列表、样式已经要让用户看到的任何内容。
- 指令的类型如下:
- 组件:带有模板的指令,此类指令是最常见的指令类型。
- 属性型指令:可以更改元素、组件或者其他指令的外观或者行为的指令。
- 结构性指令:通过添加和删除DOM元素来更改DOM布局的指令。
- 内置属性型指令
- Angular内置了一些属性型指令用来监听并修改其他HTML元素和组件的行为、属性。
- 最常见的属性型指令如下:
- NgClass:添加和删除一组CSS类。
- NgStyle:添加额删除一组Html样式。
- NgModel:将数据双向绑定到Html表单元素上。
- 将NgClass与表达式一起使用,适合根据变量来应用到不同的CSS类,如下
查看代码
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-ly-internal-directive', templateUrl: './ly-internal-directive.component.html', styleUrls: ['./ly-internal-directive.component.css'] }) export class LyInternalDirectiveComponent implements OnInit { constructor() { } // 定义一个变量,用于在模板文件中控制是否应用某个CSS类 isSpecial = false; ngOnInit(): void { } }
查看代码
<p>ly-internal-directive works!</p> //special在css文件中定义的,如果isSpecial为true,则不应用任何CSS类,否则将应用special的CSS类 <div [ngClass]="isSpecial?'':'special'">special:应用样式的时候颜色将变红哦,否则就是黑色的</div>
查看代码
// 定义special的css类,用于体现效果 .special { font-family: 'Times New Roman', Times, serif; font-size:20px; color: red; }
- 将NgClass与方法一起使用,其实还是调用k-v对象来存放一组可控制的css
查看代码
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-ly-internal-directive', templateUrl: './ly-internal-directive.component.html', styleUrls: ['./ly-internal-directive.component.css'], }) export class LyInternalDirectiveComponent implements OnInit { constructor() {} canSave = true; isSpecial = true; isUnchanged = true; // ts中类似于map或者dictionary的存在,模板页面将绑定此变量,用于控制多个CSS的显示或者隐藏 currentClasses: Record<string, boolean> = {}; ngOnInit(): void { this.setCurrentClasses(); } setCurrentClasses() { // 其中 saveable、modified都是在css类中定义的类,this.canSave和this.isUnchanged是用于控制这些calss是否被应用 // angular会将下面的key作为class名称,赋值给dom的class this.currentClasses = { saveable: !this.canSave, modified: this.isUnchanged, }; } }
查看代码
<!-- ngClass 绑定了ts文件中的一个k-v的对象,用于add/remove class--> <div [ngClass]="currentClasses">将NgClass与方法一起使用</div>
查看代码
.saveable { color: limegreen; } .modified { font-family: "Brush Script MT", cursive; font-size: 2rem; }
- 用NgStyle设置内联样式,使用逻辑操作符判断样式的设置,使用Record对象来设置一组Style
查看代码
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-ly-internal-directive', templateUrl: './ly-internal-directive.component.html', styleUrls: ['./ly-internal-directive.component.css'], }) export class LyInternalDirectiveComponent implements OnInit { constructor() {} canSave = true; isSpecial = true; isUnchanged = false; // ts中类似于map或者dictionary的存在 currentStyles: Record<string, string> = {}; ngOnInit(): void { this.setCurrentStyles(); } setCurrentStyles() { this.currentStyles = { 'font-style': this.canSave ? 'italic' : 'normal', 'font-weight': !this.isUnchanged ? 'bold' : 'normal', 'font-size': this.isSpecial ? '24px' : '12px', }; } }
查看代码
<p>------------Ng Style Demo----------------</p> <!--ngStyle绑定了一组style的Record对象,用于将多个样式绑定到此Div上--> <div [ngStyle]="currentStyles"> This div is initially italic,normal weight,and extra large(24px). </div>
- 用NgMode指令进行双向绑定
- NgModel 指令适用于ControlValueAccessor支持的元素。Angular 为所有基本 HTML 表单元素提供了ControlValueAccessor(值访问器),如果在非表单型内置元素或者第三方自定义组件上应用NgModel则必须编写一个值访问器
- 在app.module.ts中导入FormsModule,并且添加到@NgModule下面的imports列表内
- 在组件文件中定义一个变量currentName,默认值为Liye
查看代码
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-ly-internal-directive', templateUrl: './ly-internal-directive.component.html', styleUrls: ['./ly-internal-directive.component.css'], }) export class LyInternalDirectiveComponent implements OnInit { constructor() {} // 定义变量currentName用于与模板页面的Input控件进行双向绑定 currentName = 'Liye'; ngOnInit(): void { } }
- 在模板文件中将currentName显示出来,并且通过ngModel将input的值与currentName进行双向绑定
查看代码
<p>ly-internal-directive works!</p> <p>-------------Ng Model双向绑定效果---------------------</p> 双向绑定数据,输入框变化,则此处变化:<font [size]="10">{{currentName}}</font><br> <label for="example-ngModel">[(ngModel)]:</label> <input [(ngModel)]="currentName" id="example-ngModel">
- 内置结构性指令
- 结构型指令的职责是 HTML 布局。 它们塑造或重塑 DOM 的结构 ,这通常是通过添加、移除和操纵它们所附加到的宿主元素来实现的,说白了就是通过这些指令动态的创建或者销毁Html节点
- NgIf:从模板中创建或销毁子视图。
- 如下模板代码,当isActive为true时,将会生成app-item-detail这个组件的内容,否则不会生成
查看代码
<app-item-detail *ngIf="isActive" [item]="item"></app-item-detail>
- 防止null,如下模板代码,如果currentCustomer属性为null,则Angular不会显示它所在的div,否则就显示
查看代码
<div *ngIf="currentCustomer">Hello, {{currentCustomer.name}}</div>
- NgFor:为列表中的每个条目重新渲染一个节点。
- 简单一点来讲,其实就是一个for循环,然后根据内容去渲染生成新的html节点和内容
- 它可以与NgIf结合一起使用,如下,如果满足NgIf条件,则显示Default的内容
- 在ts类中定义一个string类型的数组
查看代码
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-ly-internal-directive', templateUrl: './ly-internal-directive.component.html', styleUrls: ['./ly-internal-directive.component.css'], }) export class LyInternalDirectiveComponent implements OnInit { constructor() {} items:Array<string> = ['Armi','Jimmy','Lance','Jasper','Demon']; } }
- 在模板文件中定义NgFor和NgIf的使用语法
查看代码
<p>-------------Ng For---------------------------------</p> <!--其中items在ts中定义的Array,然后在此处进行循环显示,let定义可变的变量item,i为array的索引--> <!--*ngIf控制着如果item的值为Armi,则显示Default的内容--> <div *ngFor="let item of items; let i = index"> {{ i + 1 }},{{ item }} <span *ngIf="item == 'Armi'">Default</span> </div>
- NgSwitch:一组在备用视图之间切换的指令。
- 这个指令就和我们后台的Switch几乎一样的用法
- currentItem.feature相当于需要被比较的值,每个*ngSwitchCase需要与feature比较,如果相等,那么就显示当前所在的组件,否则不显示;如果都不满足,则显示*ngSwitchDefault的组件
查看代码
<div [ngSwitch]="currentItem.feature"> <app-stout-item *ngSwitchCase="'stout'" [item]="currentItem"></app-stout-item> <app-device-item *ngSwitchCase="'slim'" [item]="currentItem"></app-device-item> <app-lost-item *ngSwitchCase="'vintage'" [item]="currentItem"></app-lost-item> <app-best-item *ngSwitchCase="'bright'" [item]="currentItem"></app-best-item> <!-- . . . --> <app-unknown-item *ngSwitchDefault [item]="currentItem"></app-unknown-item> </div>
- 自定义属性型指令(用到这块再补充)
- 自定义结构性指令(用到这块再补充)
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 清华大学推出第四讲使用 DeepSeek + DeepResearch 让科研像聊天一样简单!
· 推荐几款开源且免费的 .NET MAUI 组件库
· 实操Deepseek接入个人知识库
· 易语言 —— 开山篇
· 【全网最全教程】使用最强DeepSeekR1+联网的火山引擎,没有生成长度限制,DeepSeek本体