内建指令:
- 结构型指令(改变宿主文档结构),ngIf、ngFor、ngSwitch
- 属性型指令(改变宿主行为),ngClass、ngStyle、ngModel
自定义属性型指令
快捷键
ng-directive
directives/grid-item.directive.ts
import { Directive, ElementRef, Renderer2 } from '@angular/core';
@Directive({
selector: '[appGridItem]',
})
export class AppGridItemDirective {
constructor(private elr: ElementRef, private rd2: Renderer2) {
this.rd2.setStyle(this.elr.nativeElement, 'display', 'grid')
this.rd2.setStyle(this.elr.nativeElement, 'grid-template-areas', `'image' 'title'`)
this.rd2.setStyle(this.elr.nativeElement, 'place-items', 'center')
this.rd2.setStyle(this.elr.nativeElement, 'width', '4rem')
}
}
在app.module.ts中引入
import { AppGridItemDirective } from './directives/grid-item.directive';
@NgModule({
declarations: [
...
AppGridItemDirective
]
...
}
在app.component.html
<div appGridItem></div>