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

相关内容

热门资讯

黑科技中牌率(轰趴大菠萝十三水... 黑科技中牌率(轰趴大菠萝十三水)哈糖大菠萝十三张本来是有挂!太坑了一向有挂(2024已更新)(哔哩哔...
黑科技辅助挂(wpk稳定)wP... 黑科技辅助挂(wpk稳定)wPk一向真的是有挂!太无语了素来真的是有挂(2026已更新)(哔哩哔哩)...
黑科技辅助(aapoker牌局... AAPoKER赢率提升策略‌;黑科技辅助(aapoker牌局)AAPoKER其实是真的有挂!太实锤了...
黑科技安卓版(鱼扑克发牌规律)... 黑科技安卓版(鱼扑克发牌规律)AAPOkER竟然是有挂!太离谱了竟然是有挂(2023已更新)(哔哩哔...
黑科技脚本(aapoker规律... 黑科技脚本(aapoker规律)WPK一向真的是有挂!太嚣张了一贯是有挂(2025已更新)(哔哩哔哩...
黑科技计算(德州alphax)... 黑科技计算(德州alphax)微扑克ai一贯存在有挂!太夸张了好像是有挂(2021已更新)(哔哩哔哩...
黑科技能赢(wepoke)wp... 黑科技能赢(wepoke)wpK本然存在有挂!太夸张了一贯真的是有挂(2024已更新)(哔哩哔哩);...
黑科技辅助挂(wpk私人局)a... 黑科技辅助挂(wpk私人局)aapokER果然真的是有挂!太无语了切实真的是有挂(2023已更新)(...
黑科技模拟器(WPK辅助)aa... 黑科技模拟器(WPK辅助)aapOker一向真的有挂!太嚣张了好像真的有挂(2026已更新)(哔哩哔...
黑科技脚本(微扑克模拟器)We... 黑科技脚本(微扑克模拟器)WepOke本来真的是有挂!太实锤了其实是真的有挂(2022已更新)(哔哩...