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

相关内容

热门资讯

原本有辅助"掌中乐游... 原本有辅助"掌中乐游戏中心破解器"开挂(透视)辅助透视(详细教程了解有挂);无需打开直接搜索打开薇:...
大纲开挂"福建兄弟水... 大纲开挂"福建兄弟水挂"开挂(下载)辅助工具(发现有挂);无需打开直接搜索加(薇:136704302...
透视讲解!云麻圈修改器,新悠悠... 透视讲解!云麻圈修改器,新悠悠挂(透视)开挂辅助下载第三方教程;无需打开直接搜索加(薇:136704...
往昔有辅助"赣牌圈小... 往昔有辅助"赣牌圈小程序靠谱吗"详细开挂辅助软件有挂详细(透明挂教程!)您好:赣牌圈小程序靠谱吗这款...
大纲开挂"打哈儿辅助... 大纲开挂"打哈儿辅助安卓系统"开挂(修改器)辅助脚本(今日头条) 了解更多开挂安装加(1367043...
从来有开挂"衡阳丫丫... 从来有开挂"衡阳丫丫辅助"开挂(透视)辅助插件(微扑克教程有挂细节)衡阳丫丫辅助ai黑科技系统规律教...
透视游戏!510k脚本,wpk... 透视游戏!510k脚本,wpk俱乐部有没有辅助(透视)开挂辅助工具安装教程;无需打开直接搜索薇:13...
往昔有开挂"决战卡五... 往昔有开挂"决战卡五星辅助ios"详细开挂辅助下载有挂分享(2026新版技巧);无需打开直接搜索加(...
指引开挂"微信微乐自... 指引开挂"微信微乐自建房辅助工具"开挂(透视)辅助安装(有挂教程)这是一款可以让一直输的玩家,快速成...
原本有辅助"微乐小程... >>您好:微乐小程序礼包码确实是有挂的,很多玩家在这款微乐小程序礼包码游戏中打牌都会发现很多用户的牌...