属性型指令
创建一个自定义hightlight指令示例。
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('');
}
private highlight(color: string){
this.el.nativeElement.style.backgroundColor = color;
}
}
导入指令:
import { HighlightDirective } from './highlight.directive';
@NgModule({
declarations: [
HighlightDirective,
],
})
<span appHighlight>si3333333</span>
将值传递给highlight指令
@Input() appHighlight = '';
@HostListener('mouseenter') onMouseEnter(){
this.highlight(this.appHighlight);
}
<div>
<input type="radio" name="colors" (click)="color='lightgreen'">lightgreen
<input type="radio" name="colors" (click)="color='yellow'">yellow
<input type="radio" name="colors" (click)="color='cyan'">cyan
</div>
<span [appHighlight]="color">si3333333</span>
设置highlight指令默认值&绑定第二个值
export class HighlightDirective {
@Input() appHighlight = '';
@Input() defaultColor = '';
constructor(private el: ElementRef) {}
@HostListener('mouseenter') onMouseEnter(){
this.highlight(this.appHighlight||this.defaultColor||'red');
}
@HostListener('mouseleave') onMouseLeave(){
this.highlight('');
}
private highlight(color: string){
this.el.nativeElement.style.backgroundColor = color;
}
}
<div>
<input type="radio" name="colors" (click)="color='lightgreen'">lightgreen
<input type="radio" name="colors" (click)="color='yellow'">yellow
<input type="radio" name="colors" (click)="color='cyan'">cyan
</div>
<span [appHighlight]="color">si3333333</span>
<p [appHighlight]="color" defaultColor="violet">si3333331113</p>
☆ ngNonBindable 设置该指令,模板内的表达式求值失效。
<p ngNonBindable>2021年9月2日15:16:03 -- {{ 1 + 1 }}</p>
结构型指令
appUnless示例 unless.directive.ts
import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';
@Directive({
selector: '[appUnless]'
})
export class UnlessDirective {
private hasView = false;
constructor(
private templateRef: TemplateRef<any>,
private viewContainer: ViewContainerRef
) { }
@Input() set appUnless(condition: boolean){
if(!condition && !this.hasView){
this.viewContainer.createEmbeddedView(this.templateRef);
this.hasView = true;
}else if(condition && this.hasView){
this.viewContainer.clear();
this.hasView = false;
}
}
}
condition = false;
<p *appUnless="!condition">Lorem .</p>
<ng-template [appUnless]="!condition">
<p>Lorem .</p>
</ng-template>
|