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

相关内容

热门资讯

透视规律!wpk私人局辅助是真... 透视规律!wpk私人局辅助是真的吗,wepoker网页版透视方法,指南教程(原来真的有挂)-哔哩哔哩...
透视必备!黑侠破解wepoke... 透视必备!黑侠破解wepoker(透视)开挂辅助方法(原来真的是有挂)-哔哩哔哩黑侠破解wepoke...
透视辅助!wepoker底牌透... 透视辅助!wepoker底牌透视,wpk透视是真的吗,资料教程(好像是真的挂)-哔哩哔哩1、实时wp...
透视神器!wepoker破解是... 透视神器!wepoker破解是真的还是假的(透视)开挂辅助方法(原来真的是有挂)-哔哩哔哩进入游戏-...
透视app!sohoo竞技联盟... 透视app!sohoo竞技联盟辅助器,wepoker透视脚本免费使用视频,教程书教程(本来存在有挂)...
透视胜率!we poker辅助... 透视胜率!we poker辅助器v3.3(透视)开挂辅助方法(本来存在有挂)-哔哩哔哩一、we po...
透视总结!wpk真的有透视嘛,... 透视总结!wpk真的有透视嘛,epoker透视,方案教程(原来是真的挂)-哔哩哔哩1、上手简单,内置...
透视私人局!德普之星透视(透视... 透视私人局!德普之星透视(透视)开挂辅助软件(一直真的有挂)-哔哩哔哩进入游戏-大厅左侧-新手福利-...
透视挂透视!约局吧开挂神器是真... 透视挂透视!约局吧开挂神器是真的吗,hhpoker有没有辅助辅助,法门教程(确实是真的挂)-哔哩哔哩...
透视程序!德普之星私人局辅助免... 透视程序!德普之星私人局辅助免费(透视)开挂辅助脚本(竟然真的有挂)-哔哩哔哩1、全新机制【德普之星...