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、七千在线辅助ai机器人多...
透视神器!德州局透视脚本,xp... 透视神器!德州局透视脚本,xpoker辅助怎么用,绝活教程(原来存在有挂)-哔哩哔哩1、玩家可以在德...
透视内置!佛手在线大菠萝智能辅... 透视内置!佛手在线大菠萝智能辅助器(透视)开挂辅助器(切实是真的挂)-哔哩哔哩一、佛手在线大菠萝智能...
八分钟方案!打哈儿床将脚本,新... 八分钟方案!打哈儿床将脚本,新蜜瓜大厅免费控制器,必赢教程(有挂方法)-哔哩哔哩1)新蜜瓜大厅免费控...
透视挂!wepoker底牌透视... 透视挂!wepoker底牌透视,wpk透视工作室,手册教程(竟然有挂)-哔哩哔哩在进入wepoker...
透视软件!wepokerplu... 透视软件!wepokerplus辅助(透视)开挂辅助软件(都是真的有挂)-哔哩哔哩1、起透看视 we...
7分钟绝活!友友联盟辅助器,新... 7分钟绝活!友友联盟辅助器,新九天辅助,2025新版教程(有挂透明挂)-哔哩哔哩友友联盟辅助器软件透...
透视私人局!wpk模拟器多开,... 透视私人局!wpk模拟器多开,德普之星透视辅助软件,经验教程(其实有挂)-哔哩哔哩1、进入到德普之星...
第七分钟讲义!新九哥破解版,衢... 第七分钟讲义!新九哥破解版,衢州都莱辅助器,玩家教你(证实有挂)-哔哩哔哩1、游戏颠覆性的策略玩法,...
透视智能!wepoker辅助方... 透视智能!wepoker辅助方法(透视)开挂辅助攻略(总是真的是有挂)-哔哩哔哩1、超多福利:超高返...