templateref html内容,【Angular4+】TemplateRef和ViewContainerRef插入dom元素

#contianer

class="contianer"

(contextmenu)='onRightClickEvent($event)'

(click)="onClick()"

>

删除

一般dom元素是ElementRef包装

ng-template是TemplateRef包装

TemplateRef 在createEmbeddedView后创建ViewRef对象

通过ViewContainerRef的insert方法可以把ViewRef对象插入到dom当中

每一次插入的元素都会插入到ng-container上方

import { Component, OnInit, ElementRef, ViewContainerRef } from '@angular/core';

import { NgModule, ViewChild, TemplateRef } from '@angular/core';

import { Routes, RouterModule } from '@angular/router';

@Component({

selector: 'app-context-menu-demo',

templateUrl: './context-menu-demo.component.html',

styleUrls: ['./context-menu-demo.component.scss']

})

export class ContextMenuDemoComponent implements OnInit {

@ViewChild('contianer') container:ElementRef;

@ViewChild('newContextMenu') contextMenu:TemplateRef;//获取自定义的右击菜单元素

@ViewChild('vc',{read:ViewContainerRef}) vc:ViewContainerRef;

constructor() { }

ngOnInit() {

}

onRightClickEvent($event){

console.log('$event context Menu',$event,this.container);

let view = this.contextMenu.createEmbeddedView(null);

console.log('view',view,this.vc);

this.vc.insert(view);

$event.preventDefault();//隐藏浏览器默认的右击菜单的话,要阻止当前对象的默认事件

}

onClick(){

console.log('click');

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值