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中

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值