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

相关内容

热门资讯

透视免费!wepoker数据分... 透视免费!wepoker数据分析工具,wejoker辅助器要钱玩吗,玩家教你(一贯确实有挂)-哔哩哔...
辅助透视!wepoker破解器... 辅助透视!wepoker破解器,有没有人wepoker,必赢教程(一贯是有挂的)-哔哩哔哩;详细有没...
玩家必看教程!wepoker好... 玩家必看教程!wepoker好友助力码,wepoker有没有机器人,可靠教程(其实是有挂)-哔哩哔哩...
透视好友!wepoker提高好... 透视好友!wepoker提高好牌率,德州机器人代打脚本,爆料教程(一贯真的有挂)-哔哩哔哩;最新版2...
实测交流!hhpoker辅助软... 实测交流!hhpoker辅助软件下载,wepoker怎么挂飞机,普及教程(果然是有挂的)-哔哩哔哩;...
总算明白!哈糖大菠萝免费辅助器... 总算明白!哈糖大菠萝免费辅助器,hardrock透视工具,新版2026教程(一贯真的是有挂)-哔哩哔...
透视黑科技!aapoker万能... 透视黑科技!aapoker万能辅助器,wepoker好友助力码,AA德州教程!(其实是有挂)-哔哩哔...
一分钟秒懂!hhpoker有后... 【福星临门,好运相随】;一分钟秒懂!hhpoker有后台操控吗,aapoker如何设置胜率,wpk教...
透视真的!pokemmo修改器... 透视真的!pokemmo修改器手机版,佛手在线大菠萝技巧,必赢方法(其实真的有挂)-哔哩哔哩;1、点...
重要通知!wpk辅助,wepo... 重要通知!wpk辅助,wepoker代打辅助机器人,普及教程(其实是有挂的)-哔哩哔哩相信很多朋友都...