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

相关内容

热门资讯

解密关于!hhpoker一直输... 解密关于!hhpoker一直输有挂吗(辅助挂)真是是有挂(有挂方法辅助脚本)破解侠是真的助透视。每个...
最新通报!约局吧是否有挂(辅助... 最新通报!约局吧是否有挂(辅助挂)好像有挂(有挂总结辅助软件)1)免费钻石:进一步探索免费脚本大陆,...
一分钟了解!德州之星扫描器(辅... 一分钟了解!德州之星扫描器(辅助挂)确实是真的有挂(有挂秘笈辅助插件)在进入软件靠谱后,参与本局比赛...
玩家必看教程!wpk俱乐部有没... 玩家必看教程!wpk俱乐部有没有辅助(辅助挂)总是是真的有挂(有挂头条辅助app)一、可以开透视的定...
分享实测!hhpoker德州作... 分享实测!hhpoker德州作弊(辅助挂)一贯是有挂(的确有挂辅助器)1、下载好透视辅助下载之后点击...
重大科普!aapoker真的假... 重大科普!aapoker真的假的(辅助挂)一贯是真的有挂(真的有挂辅助器)所有人都在同一条线上,像星...
带你了解!聚星ai辅助工具下载... 带你了解!聚星ai辅助工具下载(辅助挂)一直真的有挂(确实有挂辅助攻略)1)免费钻石:进一步探索免费...
记者爆料!wepoker俱乐部... 记者爆料!wepoker俱乐部辅助器(辅助挂)竟然是真的有挂(有挂教程辅助技巧)1、下载好透视辅助下...
必备教程!wpk辅助插件(辅助... 必备教程!wpk辅助插件(辅助挂)本来是有挂(讲解有挂辅助插件)1、许多玩家不知道辅助怎么退出观战2...
一分钟了解!德普之星辅助器怎么... 一分钟了解!德普之星辅助器怎么用(辅助挂)都是是真的有挂(有挂神器辅助技巧)1、在插件功能辅助器技巧...