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

相关内容

热门资讯

透视推荐"wepok... 透视推荐"wepoker黑侠辅助器"原来真的是有辅助挂(哔哩哔哩)1、玩家可以在wepoker黑侠辅...
透视辅助"约局吧是否... 透视辅助"约局吧是否有挂"确实存在有辅助app(哔哩哔哩)1、约局吧是否有挂破解器简单,约局吧是否有...
透视分享"德州局怎么... 透视分享"德州局怎么透视"一直真的是有辅助挂(哔哩哔哩)1.德州局怎么透视 选牌创建新账号,点击进入...
透视总结"wpk模拟... 透视总结"wpk模拟器是什么"本来是真的辅助神器(哔哩哔哩)wpk模拟器是什么能透视中分为三种模型:...
透视了解"wepok... 透视了解"wepoker轻量版辅助"真是存在有辅助脚本(哔哩哔哩)在进入wepoker轻量版辅助软件...
透视详情"wpk模拟... 透视详情"wpk模拟器多开"切实真的是有辅助方法(哔哩哔哩)1、wpk模拟器多开免费脚本咨询教程、w...
透视必备"wepok... 透视必备"wepoker究竟有没有透视"切实是真的辅助方法(哔哩哔哩)1、任何wepoker究竟有没...
透视必备"poker... 透视必备"pokermaster破解版"总是真的有辅助脚本(哔哩哔哩)1、游戏颠覆性的策略玩法,独创...
透视有挂"wepok... 透视有挂"wepoker私人局有透视吗"确实是真的辅助教程(哔哩哔哩)该软件可以轻松地帮助玩家将we...
透视教你"wepok... 透视教你"wepoker有没有机器人"切实真的是有辅助神器(哔哩哔哩)所有人都在同一条线上,像星星一...