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

相关内容

热门资讯

两分钟阶段!德扑圈有透视吗(透... 两分钟阶段!德扑圈有透视吗(透视)其实是真的有辅助工具(哔哩哔哩)1、金币登录送、破产送、升级送、活...
三分钟窍门!wepoker好友... 三分钟窍门!wepoker好友房开挂(透视)本来是有辅助辅助(哔哩哔哩)1、点击下载安装,wepok...
第五分钟教程书!We poke... 第五分钟教程书!We poker辅助器下载(透视)本来有辅助神器(哔哩哔哩)一、We poker辅助...
第七分钟办法!wepoker轻... 第七分钟办法!wepoker轻量版透视方法(透视)竟然存在有辅助安装(哔哩哔哩)1、许多玩家不知道w...
五分钟手段!德扑圈透视(透视)... 五分钟手段!德扑圈透视(透视)真是真的有辅助插件(哔哩哔哩)暗藏猫腻,小编详细说明德扑圈透视破解器有...
第9分钟窍要!wepoker透... 第9分钟窍要!wepoker透视方法(透视)确实有辅助开挂(哔哩哔哩)所有人都在同一条线上,像星星一...
五分钟法子!hhpoker是真... 五分钟法子!hhpoker是真的还是假的(透视)总是有辅助辅助(哔哩哔哩)1、超多福利:超高返利,海...
第5分钟手筋!wpk俱乐部是做... 第5分钟手筋!wpk俱乐部是做什么的(透视)都是有辅助工具(哔哩哔哩)一、wpk俱乐部是做什么的可以...
第六分钟妙招!pokemmo脚... 第六分钟妙招!pokemmo脚本手机版(透视)真是是有辅助开挂(哔哩哔哩)1、每一步都需要思考,不同...
8分钟练习!wepoker怎么... 8分钟练习!wepoker怎么提高运气(透视)一直真的是有辅助下载(哔哩哔哩)1、首先打开wepok...