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

相关内容

热门资讯

一分钟了解!江西微乐南昌有辅助... 一分钟了解!江西微乐南昌有辅助,竞技联盟透视,攻略教程(了解有挂);江西微乐南昌有辅助最新软件透明挂...
一分钟了解!蜀山四川智能辅助插... 一分钟了解!蜀山四川智能辅助插件,hhpkoer辅助器,可靠教程(有挂规律);详细蜀山四川智能辅助插...
总算了解!新道游开挂辅助透视,... 总算了解!新道游开挂辅助透视,aapoker公共底牌,德州教程(有挂透明挂)是一款可以让一直输的玩家...
推荐一款!微乐小程序辅助收费,... 推荐一款!微乐小程序辅助收费,pokemmo脚本辅助器,2025教程(有人有挂);AI辅助机器人普及...
重磅来袭!大唐山西辅助软件,f... 重磅来袭!大唐山西辅助软件,fishpoker透视,可靠教程(证实有挂),大唐山西辅助软件是用手机号...
必备辅助推荐!广丰510k辅助... 必备辅助推荐!广丰510k辅助插件,wepoker游戏下载,德州论坛(讲解有挂)是一款可以让一直输的...
总算了解!小程序卡五星辅助,w... 总算了解!小程序卡五星辅助,wpk软件是正规的吗,AI教程(有挂存在);一、小程序卡五星辅助AI软件...
一分钟揭秘!孝感卡五星辅助,w... 一分钟揭秘!孝感卡五星辅助,wepoker有透视吗,必赢方法(有挂教学);1、让任何用户在无需AI插...
最新通报!悟空大厅辅助器,we... 最新通报!悟空大厅辅助器,we poker辅助器,详细教程(讲解有挂);悟空大厅辅助器软件透明挂是一...
科普常识!518互娱脚本,we... 科普常识!518互娱脚本,wejoker手机版透视脚本,AI教程(有挂秘籍)是一款可以让一直输的玩家...