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、玩家可以在新九天作必弊...
截至目前!金虎爷辅助器,新51... 截至目前!金虎爷辅助器,新518互游插件下载-真是是真的有辅助神器(哔哩哔哩)1、下载好新518互游...
截至发稿!蜀山四川辅助脚本,福... 截至发稿!蜀山四川辅助脚本,福建天天开心辅助工具下载-真是真的是有辅助app(哔哩哔哩)1、上手简单...
随着!杭州都莱大菠萝买了挂有用... 随着!杭州都莱大菠萝买了挂有用吗,小唐家乐园辅助-真是是有辅助软件(哔哩哔哩)1、游戏颠覆性的策略玩...
2026版教学!欢乐掌心英山修... 2026版教学!欢乐掌心英山修改器,越乡游义乌辅助器免费试用-一直是真的有辅助挂(哔哩哔哩)1、上手...
教学辅助挂!微信呢小程序游戏辅... 教学辅助挂!微信呢小程序游戏辅助器,闲来山水广西辅助-好像确实有辅助技巧(哔哩哔哩)1.微信呢小程序...
为切实保障!衢州都莱辅助器免费... 为切实保障!衢州都莱辅助器免费,四川途游小程序辅助-总是存在有辅助工具(哔哩哔哩)1、很好的工具软件...
不少玩家反映!丰城双剑新版最强... 不少玩家反映!丰城双剑新版最强高分攻略,边锋老友填大坑辅助-原来真的有辅助攻略(哔哩哔哩)1、丰城双...
据悉!杭州都莱大菠萝有挂吗,创... 据悉!杭州都莱大菠萝有挂吗,创思维激k看底牌辅助-一直是真的有辅助器(哔哩哔哩);杭州都莱大菠萝有挂...
透视脚本!玉海楼茶苑游戏攻略,... 透视脚本!玉海楼茶苑游戏攻略,开心泉州免费辅助器-其实真的是有辅助软件(哔哩哔哩)1、打开软件启动之...