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

相关内容

热门资讯

黑科技辅助挂(epoker外挂... 您好,云扑克德州这款游戏可以开挂的,确实是有挂的,需要了解加微【136704302】很多玩家在这款游...
黑科技讲解(云扑克cloudp... 黑科技讲解(云扑克cloudpoker)德扑之星素来是真的有挂!太嚣张了果然真的是有挂(2023已更...
黑科技最新(Wepoke安装)... 黑科技最新(Wepoke安装)AAPOKEr一贯是有挂!太实锤了原先存在有挂(2025已更新)(哔哩...
黑科技游戏(微扑克钻石)红龙p... 黑科技游戏(微扑克钻石)红龙poker从来是有挂!太无语了总是真的有挂(2025已更新)(哔哩哔哩)...
黑科技辅助挂(Wepoke技术... 黑科技辅助挂(Wepoke技术)aaPoker原来真的是有挂!太无语了切实真的有挂(2025已更新)...
黑科技辅助挂(Wepoke检测... 黑科技辅助挂(Wepoke检测)aapOKER从前真的是有挂!太离谱了切实有挂(2023已更新)(哔...
黑科技计算(Wepoke轻量版... 黑科技计算(Wepoke轻量版)WPk真是真的有挂!太实锤了原本有挂(2026已更新)(哔哩哔哩);...
黑科技攻略(Wepoke代打)... 黑科技攻略(Wepoke代打)wopoker原先真的有挂!太离谱了原生存在有挂(2025已更新)(哔...
黑科技美元局(德扑胜率)哈糖大... 黑科技美元局(德扑胜率)哈糖大菠萝一贯真的有挂!太离谱了一直有挂(2024已更新)(哔哩哔哩);亲真...
黑科技私人局(德扑之星介绍)a... 1、黑科技私人局(德扑之星介绍)aAPOKER本来是有挂!太坑了竟然是有挂(2025已更新)(哔哩哔...