美文网首页
【Angular4+】TemplateRef和ViewConta

【Angular4+】TemplateRef和ViewConta

作者: 匿于烟火中 | 来源:发表于2019-04-22 16:53 被阅读0次
<ng-container #vc>
    <div 
    #contianer
    class="contianer"
    (contextmenu)='onRightClickEvent($event)'
    (click)="onClick()"
    >
    </div>
</ng-container>

<ng-template #newContextMenu>
  <!--  id="newContextMenu"  -->
  <div>
    <button  (click)="bindDeleteAction()">
          删除
     </button>
</div>
</ng-template>

一般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<any>;
  @ViewChild('newContextMenu') contextMenu:TemplateRef<any>;//获取自定义的右击菜单元素
  @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');
  }

}

相关文章