Angular4+使用指令(Directive)动态创建组件
需求:鼠标右击某一区域显示活动导航类似这种。
分析:结合Angular的使用经验,采用指令来动态创建组件会比较好实现这个需求。首先要禁止网页鼠标右击时的原生事件,同时动态创建一个新组件,这个组件创建的位置要随着鼠标的移动不断改变,最后要销毁这个组件。
实现:ng g directive smart (创建指令)
ng g c smart(创建组件)
smart.directive.ts文件中
import {
Directive,
HostListener,
ComponentRef,
ComponentFactory,
ViewContainerRef,
ComponentFactoryResolver,
} from '@angular/core';
import { SmartComponent } from "./smart";
@Directive({
selector: '[appSmart]'
})
export class SmartDirective {
public mouseDistance: any;
public smartTag: ComponentRef<SmartComponent>;
public factory: ComponentFactory<SmartComponent>;
//监听鼠标的右击事件,并禁止,同时获取鼠标的clientX位置,clientY此处不需要。
@HostListener('contextmenu', ['$event']) ban(event) {
event.preventDefault();
this.mouseDistance = event.clientX + 'px';
this.onClick();
}
constructor(private _viewContainer: ViewContainerRef, private _resolve: ComponentFactoryResolver) {
//获取组件工厂
this.factory = this._resolve.resolveComponentFactory(SmartComponent);
}
@HostListener('click') onClick() {
//清空view
this._viewContainer.clear();
//创建组件
this.smartTag = this._viewContainer.createComponent(this.factory);
//把鼠标的clientX值传给这个组件
this.smartTag.instance.LeftDistance = this.mouseDistance;
}
@HostListener('mouseleave') onmouseleave() {
if (this.smartTag) {
//销毁这个组件
this.smartTag.destroy();
}
}
}
smart.ts文件
部分html
注意事项:声明smart组件时,不仅要添加到declarations中,也需要添加到entryComponents中