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

相关内容

热门资讯

玩家必知教程"微信超... 【亲,微信超级3+1辅助 这款游戏可以开挂的,确实是有挂的,很多玩家在这款微信超级3+1辅助中打牌都...
专业讨论"新道游拼十... >>您好:新道游拼十辅助器确实是有挂的,很多玩家在这款新道游拼十辅助器游戏中打牌都会发现很多用户的牌...
透视讲解"多乐游戏修... 透视讲解"多乐游戏修改器"开挂(脚本)辅助脚本今日头条-黑科技教程;无需打开直接搜索薇:136704...
总算了解"三江互娱辅... 三江互娱辅助 无需打开直接搜索微信:136704302本司针对手游进行,选择我们的四大理由: 1、软...
分辨真假"微信小游戏... 分辨真假"微信小游戏辅助器"开挂(软件)辅助软件真是有挂-新2026版;无需打开直接搜索加薇1367...
关于"werplan... 关于"werplan辅助软件"开挂(下载)辅助下载有挂助手-AI教程>>您好:软件加13670430...
解密关于"蜀门手游辅... 解密关于"蜀门手游辅助免费脚本"开挂(脚本)辅助脚本有挂实锤-AI教程蜀门手游辅助免费脚本ai黑科技...
科普分享"wpk德州... 科普分享"wpk德州局怎么透视"开挂(插件)辅助插件有挂方略-辅助教程;无需打开直接搜索打开薇:13...
2024教程"微信雀... 2024教程"微信雀神小程序插件"开挂(下载)辅助下载确实有挂-大神讲解;无需打开直接搜索加薇136...
盘点一款"宝宝浙江辅... 大家好,今天小编来为大家解答宝宝浙江辅助工具这个问题咨询软件客服可以免费测试直接加微信(136704...