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私人局有... wpk私人局有透视吗AI 游戏攻略黑科技上线本地缓存功能,离线查阅能力开挂。提前下载对应游戏攻略数据...
关于开挂!we poker辅助... 关于开挂!we poker辅助器v3.3,德普之星有挂么辅助工具(原生真的有开挂)主打本地运行的 A...
分享认知辅助器!德普辅助器怎么... 德普辅助器怎么用AI 游戏攻略黑科技上线本地缓存功能,离线查阅能力开挂。提前下载对应游戏攻略数据包,...
热门推荐透视!wpk系统是否存... 『标题:当前标题』主打赛后复盘的 AI 游戏攻略黑科技走红,对局总结能力开挂。上传对局回放或者战绩截...
玩家必看开挂!wpk辅助,德扑... 玩家必看开挂!wpk辅助,德扑之星真的有挂吗下载(原来真的是有开挂)主打本地运行的 AI 黑科技工具...
热点讨论辅助!wpk软件是正规... 您好,热点讨论辅助!wpk软件是正规的吗,微扑克到底有没有挂下载(好像真的有辅助)这款游戏可以开挂的...
专业教程辅助!德普之星辅助功能... 『标题:当前标题』主打赛后复盘的 AI 游戏攻略黑科技走红,对局总结能力开挂。上传对局回放或者战绩截...
重大通报透视挂!wepoker... 一款 AI 游戏攻略黑科技工具上线,查攻略效率直接开挂。它整合版本更新、装备搭配、BOSS 打法、牌...
我来分享辅助器!wepoker... 您好:wepoker透视苹果系统这款游戏可以开挂的,确实是有挂的,很多玩家在这款游戏中打牌都会发现很...
发现一款透视!德扑之星的辅助工... 很多人使用云端 AI 时,都担心德扑之星的辅助工具介绍、内部资料上传带来隐私风险。这款本地运行的 A...