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、全新机制【来旺...
最新通报!微乐三打一透视功能a... 最新通报!微乐三打一透视功能app,微乐三打一一贯存在有透视app(有辅助挂分享)一、微乐三打一可以...
教程辅助!江山大厅辅助功能教程... 教程辅助!江山大厅辅助功能教程,江山大厅切实是有辅助教程(有辅助挂猫腻)1、江山大厅模拟器是什么优化...
专业讨论!永乐跑胡子辅助功能脚... 专业讨论!永乐跑胡子辅助功能脚本,永乐跑胡子原来存在有辅助脚本(有辅助挂实锤)1、永乐跑胡子透视辅助...
我来向大家传授!微友约局开挂功... 我来向大家传授!微友约局开挂功能教程,微友约局总是有开挂教程(真实有辅助挂)1、我来向大家传授!微友...
一分钟教你!宝宝浙江麻将透视功... 一分钟教你!宝宝浙江麻将透视功能插件,宝宝浙江麻将确实存在有透视插件(真的有辅助挂)暗藏猫腻,小编详...
今日头条!开云棋牌透视挂功能插... 今日头条!开云棋牌透视挂功能插件,开云棋牌真是真的有透视挂插件(有辅助挂实锤)1、操作简单,无需开云...
推荐一款!天酷大厅开挂功能工具... 推荐一款!天酷大厅开挂功能工具,天酷大厅确实真的有开挂工具(有辅助挂攻略)1、天酷大厅辅助软件下载优...
实测交流!三打哈开挂功能技巧,... 实测交流!三打哈开挂功能技巧,三打哈果然是真的有开挂技巧(证实有辅助挂)三打哈能透视中分为三种模型:...
传递经验!24棋牌辅助器功能技... 传递经验!24棋牌辅助器功能技巧,24棋牌切实真的是有辅助器技巧(果真有辅助挂)1、进入到24棋牌是...