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...
一起来探讨!258透视脚本(外... 一起来探讨!258透视脚本(外挂),258原来真的是有外挂技巧1、金币登录送、破产送、升级送、活动送...
玩家必看科普!雀友圈斗地主有没... 玩家必看科普!雀友圈斗地主有没有挂吗(辅助挂),雀友圈斗地主竟然有辅助挂脚本1、很好的工具软件,可以...
每日必看教程!打两圈透视开挂(... 每日必看教程!打两圈透视开挂(作弊器),打两圈确实真的有作弊器教程1、打两圈破解器简单,打两圈机器人...
大神推荐!天天微乐可以装挂吗(... 大神推荐!天天微乐可以装挂吗(辅助器),天天微乐切实是有辅助器教材1、操作简单,无需天天微乐手机版透...
玩家必看攻略!荆门麻将透视辅助... 玩家必看攻略!荆门麻将透视辅助(透视),荆门麻将其实是有透视举措1、这是跨平台的荆门麻将轻量版有透视...
一分钟揭秘!牌友游戏开挂透视教... 一分钟揭秘!牌友游戏开挂透视教程(辅助挂),牌友游戏一直存在有辅助挂技法1、用户打开应用后不用登录就...
一分钟带你了解!汇友互动怎么开... 一分钟带你了解!汇友互动怎么开挂(外挂),汇友互动都是真的是有外挂方法1、不需要AI权限,帮助你快速...
总算了解!欢乐掌心麻将有挂吗确... 总算了解!欢乐掌心麻将有挂吗确实有挂(外挂),欢乐掌心麻将好像真的有外挂学习1、欢乐掌心麻将有没有辅...
玩家必看分享!边锋舟山棋牌真的... 玩家必看分享!边锋舟山棋牌真的有挂(透视挂),边锋舟山棋牌原来是真的有透视挂模块1、许多玩家不知道边...