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透视脚本,wpk有辅助吗,积累教程(竟然是真的挂)-哔哩哔哩1、德州局...
透视德州版!pokemmo手机... 透视德州版!pokemmo手机脚本辅助器(透视)开挂辅助插件(本来真的是有挂)-哔哩哔哩;1、玩家可...
透视透视!wepoker免费脚... 透视透视!wepoker免费脚本咨询,wpk免费辅助,诀窍教程(本来真的是有挂)-哔哩哔哩运wepo...
透视智能!hhpoker脚本(... 透视智能!hhpoker脚本(透视)开挂辅助工具(果然存在有挂)-哔哩哔哩1、hhpoker脚本系统...
透视总结!we-poker辅助... 透视总结!we-poker辅助,wejoker内置辅助,手段教程(竟然真的是有挂)-哔哩哔哩1、每一...
透视了解!德州透视是真的吗,w... 透视了解!德州透视是真的吗,wepoker私人局俱乐部,技法教程(都是存在有挂)-哔哩哔哩1、该软件...
透视透视!wpk系统是否存在辅... 透视透视!wpk系统是否存在辅助行为(透视)开挂辅助攻略(都是真的是有挂)-哔哩哔哩wpk系统是否存...
透视中牌率!黑侠破解wepok... 透视中牌率!黑侠破解wepoker,德普之星私人局透视,手册教程(原来真的是有挂)-哔哩哔哩1、很好...
透视ai代打!poker ma... 透视ai代打!poker master辅助(透视)开挂辅助插件(竟然存在有挂)-哔哩哔哩1)poke...
透视脚本!哈糖大菠萝有挂吗5个... 透视脚本!哈糖大菠萝有挂吗5个常用方法,wepoker看底牌,窍门教程(竟然真的有挂)-哔哩哔哩1、...