Angular中@Component在模板中使用`require(...)`无法正常工作
创始人
2024-10-31 00:01:12
0

推荐使用import而不是require来加载模块。如果非要使用require,可以使用Angular提供的NgModuleFactoryLoader来动态加载组件。

示例代码:

使用import加载模块:

import { Component } from '@angular/core';
import { MyService } from './my.service';

@Component({
  selector: 'app-my-component',
  template: `
    
Welcome, {{ name }}!
`, }) export class MyComponent { constructor(private myService: MyService) {} name = this.myService.getName(); loadMyOtherComponent() { import('./my-other-component/my-other-component.component').then(module => { // Do something with the module, such as rendering the dynamic component }); } }

使用NgModuleFactoryLoader动态加载组件:

import { Component, NgModuleFactoryLoader, ViewChild, ViewContainerRef } from '@angular/core';

@Component({
  selector: 'app-my-component',
  template: `
    
`, }) export class MyComponent { @ViewChild('target', { read: ViewContainerRef }) target: ViewContainerRef; constructor(private loader: NgModuleFactoryLoader) {} loadMyOtherComponent() { this.loader.load('./my-other-component/my-other-component.module#MyOtherComponentModule').then(factory => { const moduleRef = factory.create(this.target.injector); const componentFactory = moduleRef.componentFactoryResolver.resolveComponentFactory(MyOtherComponent); this.target.clear(); this.target.createComponent(componentFactory); }); } }

相关内容

热门资讯

现有说明如下!werplan辅... 现有说明如下!werplan辅助软件(透视)果然真的是有辅助修改器(有挂秘籍)-哔哩哔哩1、点击下载...
经核实!wpk模拟器是什么(透... 经核实!wpk模拟器是什么(透视)原来有辅助工具(有挂辅助)-哔哩哔哩1、上手简单,内置详细流程视频...
目前来看!pokemmo脚本辅... 目前来看!pokemmo脚本辅助器(透视)好像是真的辅助安装(有挂透视)-哔哩哔哩1、完成pokem...
透视好友房!aapoker怎么... 透视好友房!aapoker怎么拿好牌(透视)果然是有辅助下载(存在有挂)-哔哩哔哩1、实时aapok...
据玩家消息!红龙poker辅助... 据玩家消息!红龙poker辅助工具(透视)好像是有辅助软件(证实有挂)-哔哩哔哩1、实时红龙poke...
透视最新!xpoker辅助工具... 透视最新!xpoker辅助工具(透视)本来有辅助神器(有挂辅助)-哔哩哔哩1、起透看视 xpoker...
透视游戏!wepoker钻石怎... 透视游戏!wepoker钻石怎么看底牌(透视)果然有辅助平台(有挂工具)-哔哩哔哩wepoker钻石...
透视挂!wepoker透视脚本... 透视挂!wepoker透视脚本免费下载(透视)本来有辅助软件(有挂实锤)-哔哩哔哩1)wepoker...
据目击者称!wejoker透视... 据目击者称!wejoker透视方法(透视)果然是真的辅助工具(了解有挂)-哔哩哔哩1、许多玩家不知道...
透视系统!hhpoker免费辅... 透视系统!hhpoker免费辅助器(透视)原来是真的辅助插件(有挂实锤)-哔哩哔哩1.hhpoker...