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

相关内容

热门资讯

实测教程"广东雀神智... 实测教程"广东雀神智能插件智能价格"开挂(下载)辅助下载有挂攻略-技巧教程;亲,广东雀神智能插件智能...
大家学习交流"西兵辅... 大家学习交流"西兵辅助器"开挂(透视)辅助透视有挂工具-线上教程;无需打开直接搜索薇:1367043...
分享一款"新西游拼十... 分享一款"新西游拼十辅助器"开挂(安装)辅助安装今日头条-必备教程 【无需打开直接搜索加薇13670...
分享一款"创思维激k... 分享一款"创思维激k辅助插件"开挂(脚本)辅助脚本有挂分享-线上教程创思维激k辅助插件ai黑科技系统...
1.9分钟了解"有哪... 【亲,有哪些免费的wpk辅助码 这款游戏可以开挂的,确实是有挂的,很多玩家在这款有哪些免费的wpk辅...
今日百科"茶馆辅助软... 今日百科"茶馆辅助软件"开挂(下载)辅助下载有挂方针-科技教程 >>您好:软件加薇136704302...
必知教程"决战十三辅... 必知教程"决战十三辅助器"开挂(透视)辅助透视有挂解惑-2026新版技巧 了解更多开挂安装加(136...
揭秘几款"金虎爷辅助... 大家好,今天小编来为大家解答金虎爷辅助器这个问题咨询软件客服可以免费测试直接加微信(13670430...
透视教学"星悦游戏辅... 透视教学"星悦游戏辅助论坛"开挂(软件)辅助软件有人有挂-规律教程;无需打开直接搜索薇:136704...
一分钟秒懂"poke... 一分钟秒懂"pokemmo辅助器脚本下载"开挂(透视)辅助透视有挂总结-必胜教程 【无需打开直接搜索...