javascript - 在我的新 div 中创建的 angular 指令加载组件而不是在外部
问题描述
我有各种工具提示,所以我决定使用directive
. 它工作正常。但问题是它没有加载到主机内部或附加div
。不加载component
创建的子 div,我发现没有用。
有人请帮帮我吗?
这是我的指令:
import { DOCUMENT } from '@angular/common';
import {
Directive,
ElementRef,
Input,
OnInit,
SimpleChanges,
HostListener,
ViewContainerRef,
Renderer2,
Inject,
ViewChild,
ComponentFactoryResolver,
} from '@angular/core';
import { ComponentLoaderService } from './component-loader.service';
export interface LoaderConfig {
componentName: string;
action: string;
}
@Directive({
selector: '[appComponentLoader]',
})
export class ComponentLoaderDirective implements OnInit {
@Input() loaderConfig: LoaderConfig;
private _loaderActive = false;
@ViewChild('container', { read: ViewContainerRef })
viewContainerRef: ViewContainerRef;
constructor(
private componentLoader: ComponentLoaderService,
private elementRef: ElementRef,
private renderer: Renderer2,
@Inject(DOCUMENT) private document,
private vr: ViewContainerRef,
private componentFactoryResolver: ComponentFactoryResolver
) {}
ngOnInit() {
// this.loaderConfig.action = 'mouseenter'
let child = document.createElement('div');
child.style.border = '1px solid red';
this.renderer.appendChild(this.elementRef.nativeElement, child); //my child should hold component
}
ngOnChanges(changes: SimpleChanges) {
console.log('recived component name:', this.loaderConfig.action);
// this.embedComponent();
}
@HostListener('mouseenter') mouseover() {
if (this.loaderConfig.action === 'mouseenter') {
this.embedComponent();
} else {
return;
}
}
@HostListener('mouseleave') mouseleave() {
if (this.loaderConfig.action === 'mouseenter') {
this.removeComponent();
} else return;
}
@HostListener('click') onClick() {
if (this.loaderConfig.action === 'click') {
this.toggleLoader();
} else {
return;
}
}
embedComponent() {
const componentRef = this.componentLoader.loadComponent(
this.loaderConfig.componentName
);
if (componentRef) {
this.vr.clear();
this.vr.createComponent(componentRef); //just appending outside somewhere
}
}
removeComponent() {
this.vr.detach();
}
toggleLoader() {
this._loaderActive = !this._loaderActive;
if (this._loaderActive) {
this.embedComponent();
} else {
this.removeComponent();
}
}
}
我如何在我创建的孩子中加载组件?提前致谢
解决方案
您可以简单地在指令的宿主内移动动态呈现的组件的宿主元素。
this.vr.clear();
const ref = this.vr.createComponent(componentRef); //just appending outside somewhere
this.renderer.appendChild(this.elementRef.nativeElement, ref.location.nativeElement);
推荐阅读
- c# - Dropbox v2 SDK 点网删除共享链接
- prolog - Prolog 不计算列表的变量
- java - 在执行外部进程时更新我的 JavaFX 应用程序的视图
- angular - How does mat-autocomplete classList Input work?
- php - 使用 NICE 值运行 php-fpm 池
- javascript - 在 React 中将数据传递给组件(道具)
- laravel - 关于在 Laravel 中使用 Upsert 时插入关系的问题
- sql - 您可以在窗口函数中包含除法吗(红移)
- angular - 当 observable 以角度执行完所有步骤时,如何执行一段代码?
- redux - 将所有 saga 动作包装在一个通用的生成器函数中