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、该软件可以轻松地帮...
七分钟了解!新二号辅助软件价格... 七分钟了解!新二号辅助软件价格!竟然是真的有辅助技巧(有挂神器)-哔哩哔哩新二号辅助软件价格破解侠是...
2分钟了解!欢乐茶馆辅助!好像... 2分钟了解!欢乐茶馆辅助!好像有辅助攻略(有挂技巧)-哔哩哔哩1、欢乐茶馆辅助免费脚本咨询教程、欢乐...
7分钟了解!广东雀神智能插件辅... 7分钟了解!广东雀神智能插件辅助脚本!其实有辅助神器(果真有挂)-哔哩哔哩该软件可以轻松地帮助玩家将...
5分钟了解!微信老铁13水辅助... 5分钟了解!微信老铁13水辅助!原来是有辅助软件(有挂分析)-哔哩哔哩1、完成微信老铁13水辅助辅助...
第1分钟了解!熊猫辅助官网下载... 第1分钟了解!熊猫辅助官网下载安装!一直是真的有辅助工具(有挂技巧)-哔哩哔哩1、玩家可以在熊猫辅助...
第六分钟了解!星悦软件辅助!总... 第六分钟了解!星悦软件辅助!总是是有辅助神器(有挂助手)-哔哩哔哩1、星悦软件辅助免费辅助多个强度级...
三分钟了解!功夫川麻小程序有挂... 三分钟了解!功夫川麻小程序有挂吗!确实真的是有辅助教程(有挂技术)-哔哩哔哩1、功夫川麻小程序有挂吗...
第二分钟了解!浙江游戏大厅透视... 第二分钟了解!浙江游戏大厅透视辅助器!总是是真的有辅助方法(讲解有挂)-哔哩哔哩浙江游戏大厅透视辅助...
第五分钟了解!皮皮四川游戏挂!... 第五分钟了解!皮皮四川游戏挂!其实是有辅助脚本(有挂工具)-哔哩哔哩1、超多福利:超高返利,海量正版...