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); }); } }

相关内容

热门资讯

推荐一款!wpk模拟器多开,微... 很多人使用云端 AI 时,都担心wpk模拟器多开、内部资料上传带来隐私风险。这款本地运行的 AI 黑...
玩家必看秘籍!we poker... 玩家必看秘籍!we poker游戏下,微扑克到底有没有挂工具(往昔真的有开挂)主打本地运行的 AI ...
玩家教你!wepoker辅助分... 玩家教你!wepoker辅助分析器,德扑之星透视软件下载下载(一直存在有透视)AI 是一款可以让一直...
一分钟揭秘!wepoker透视... 您好,一分钟揭秘!wepoker透视器免费,wepoker有没有透视挂下载(原来是真的有透视挂)这款...
重要通知!we-poker辅助... 您好,重要通知!we-poker辅助,微扑克到底有没有透视挂安装(本然存在有透视挂)这款游戏可以开挂...
一分钟带你了解!WPK脚本,w... AI 黑科技赛道又上新,这款智能处理工具堪称效率开挂,专门面向短视频创作者打造。它打通脚本撰写、AI...
必备攻略!wepoker亲友圈... 本地部署 AI 黑科技工具迎来新版本,不用上传文件到云端就能完成wepoker亲友圈有用吗解析、 A...
一分钟了解!!WPK真假,微扑... 『标题:当前标题』主打赛后复盘的 AI 游戏攻略黑科技走红,对局总结能力开挂。上传对局回放或者战绩截...
我来向大家传授!wepoker... 很多人使用云端 AI 时,都担心wepoker破解工具、内部资料上传带来隐私风险。这款本地运行的 A...
玩家必看科普!德普之星辅助器a... 很多人使用云端 AI 时,都担心德扑之星透视辅助插件、内部资料上传带来隐私风险。这款本地运行的 AI...