指令
Angular的指令概念跟AngularJS的指令差不多,最重要的区别在于Angular中的组件继承指令,算是特殊的指令。我们看下用指令的方式去写组件的简单例子:
import { Directive,Input,ElementRef } from '@angular/core';
@Directive({
selector: 'hello'
})
export class HelloDirective {
@Input() name: string;
constructor(private el: ElementRef) {}
public ngOnInit(): void {
this.el.nativeElement.innerText = `hello ${this.name}!`;
}
}
// 使用组件指令
<hello name="Yecao"></hello>
// 渲染结果
<hello> hello, Yecao! </hello>
不要忘记在使用前先在模块中声明哦,我觉得这是Angular最烦人的一点。
除此之外,还有属性指令和结构指令,属性指令只改变元素的样式或者行为。要写成属性指令,需要在selector
属性中用[]
包裹起来。来看简单地例子:
import { Directive, ElementRef, Renderer2 } from '@angular/core';
@Directive({
selector: '[highLight]'
})
export class HighLightDirective {
constructor(private el: ElementRef, private renderer2: Renderer2) { }
ngAfterViewInit() {
this.renderer2.addClass(this.el.nativeElement, 'highlight');
}
}
// 使用属性指令
<p highLight> 这一段会高亮显示 </p>
结构指令就是模板中提到的*ngIf,*ngFor等指令,它修改了DOM结构。举个例子,重写*ngIf:
import { Directive, Input, ViewContainerRef, TemplateRef } from '@angular/core';
@Directive({
selector: '[myIf]'
})
export class MyIfDirective {
constructor(private templateRef: TemplateRef<any>,
private viewContainer: ViewContainerRef) { }
@Input() set appMyIf(condition: boolean) {
if (condition) {
this.viewContainer.createEmbeddedView(this.templateRef);
} else {
this.viewContainer.clear();
}
}
}
// 使用结构指令
<p *myIf="false"> 这一段不会显示 </p>
想要整理更多的碎片知识,扫码关注下面的公众号,让我们在哪里接着唠!