angular提供两种内置指令:结构指令和属性指令
内置指令仅仅使用了公共 API。也就是说,它们没有用到任何其它指令无权访问的私有 API。
通常应用在元素或者组件上,监听他们的行为、attribute和property,就像元素属性一样。
ngClass
: 同时添加或者删除一个或者多个css类
ngStyle
:可以通过style属性绑定的方式更改单个样式;也可以通过ngStyle添加对象的方式设置多个样式
ngModel
: 双向数据绑定
使用 ngModel 指令,必须先导入 FormsModule 并将其添加到 NgModule 的 imports 列表中
因此 NgModel
指令仅适用于通过 ControlValueAccessor 适配过这种协议的元素。Angular 已经为所有基本的 HTML 表单元素提供了值访问器。
结构指令通过添加、移除它们的宿主元素来塑造和控制dom结构。
内置结构指令前面要加上*。
当指令没有合适的宿主,可以用<ng-container>
对元素进行分类
ngIf
:添加或者删除元素。
ngIf删除元素会从dom结构中删除该元素以及这个元素的子结构
应用:防范空指针错误。
<div *ngIf="currentCustomer">Hello, {{currentCustomer.name}}</div>
ngFor
:重复指令。用来显示条目列表的方法。
<div *ngFor="let item of items; let i=index">{{i + 1}} - {{item.name}}</div>
ngSwitch
: 官网
创建指令类文件
ng generate directive highlight
将highlight.directive.ts
的内容更改如下
import { Directive, ElementRef, HostListener } from ‘@angular/core‘;
// @HostListener装饰器让你订阅属性指令所在宿主dom元素的事件。
// 你可以在指令的构造函数中使用 ElementRef 来注入宿主 DOM 元素的引用,也就是你放置 appHighlight 的那个元素。
?
@Directive({
selector: ‘[appHighlight]‘
})
export class HighlightDirective {
@HostListener(‘mouseenter‘) onmouseenter() {
console.log(‘enter‘)
}
?
@HostListener(‘mouseleave‘) onmouseleave() {
console.log(‘leave‘)
}
// 构造函数接收一个参数:el,通过el可以直接访问宿主元素
// 当在宿主元素上面发现appHighlight属性,就会创建一个HighlightDirective实例
constructor(el: ElementRef) {
console.log(el)
el.nativeElement.style.backgroundColor = ‘yellow‘;
}
?
}
使用:
<p appHighlight>我使用了自定义指令</p>
import { Directive, ElementRef, HostListener } from ‘@angular/core‘;
?
@Directive({
selector: ‘[appHighlight]‘
})
export class HighlightDirective {
constructor(private el: ElementRef) { }
?
@HostListener(‘mouseenter‘) onMouseEnter() {
this.highlight(‘yellow‘);
}
?
@HostListener(‘mouseleave‘) onMouseLeave() {
this.highlight(null);
}
?
private highlight(color: string) {
this.el.nativeElement.style.backgroundColor = color;
}
}
绑定@input属性
import { Directive, ElementRef, HostListener, Input } from ‘@angular/core‘;
?
@Directive({
selector: ‘[appHighLightWithInput]‘
})
export class HighLightWithInputDirective {
绑定@input别名
原文:https://www.cnblogs.com/lovlyGir/p/14800151.html