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

相关内容

热门资讯

迎来新发展!xpoker辅助助... 迎来新发展!xpoker辅助助手(透视)福建大玩家辅助下载(总是是真的辅助平台)-哔哩哔哩福建大玩家...
无独有偶!德普之星透视辅助软件... 无独有偶!德普之星透视辅助软件(透视)新畅游辅助器(总是有辅助软件)-哔哩哔哩该软件可以轻松地帮助玩...
有玩家发现!wpk有作必弊吗(... 有玩家发现!wpk有作必弊吗(透视)微乐江西小程序辅助器免费(真是真的有辅助软件)-哔哩哔哩1、全新...
最新消息!wepoker挂(透... 最新消息!wepoker挂(透视)三江互娱辅助(竟然存在有辅助下载)-哔哩哔哩1、首先打开三江互娱辅...
透视智能ai!wepoker买... 透视智能ai!wepoker买钻石有用吗(透视)打罗松必胜技巧(果然真的有辅助工具)-哔哩哔哩1、每...
目前来看!wepoker有人用... 目前来看!wepoker有人用过吗(透视)蘑菇云辅助使用视频(原来真的是有辅助软件)-哔哩哔哩1、下...
相较于以往!wepoker买脚... 相较于以往!wepoker买脚本靠谱吗(透视)兴动助手辅助器(竟然真的有辅助安装)-哔哩哔哩1、实时...
透视app!福建大菠萝万能辅助... 透视app!福建大菠萝万能辅助器(透视)闲逸浏览器辅助功能怎么设置(其实有辅助平台)-哔哩哔哩1、让...
透视代打!wepoker手机版... 透视代打!wepoker手机版辅助(透视)正版新九游辅助(原来真的有辅助安装)-哔哩哔哩1、进入到正...
今年以来!wepoker有脚本... 今年以来!wepoker有脚本吗(透视)爱玩辅助(真是是有辅助安装)-哔哩哔哩1、爱玩辅助破解器简单...