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

相关内容

热门资讯

揭秘!新呼啦麻将辅助ai透视挂... 揭秘!新呼啦麻将辅助ai透视挂攻略,新呼啦麻将一贯是有开挂(有辅助挂教学)新呼啦麻将能透视中分为三种...
避坑细节!朋友局辅助ai透视挂... 避坑细节!朋友局辅助ai透视挂技巧,朋友局竟然真的有辅助器(详细教程辅助)1、打开软件启动之后找到中...
科普!闲来广东麻将辅助ai透视... 科普!闲来广东麻将辅助ai透视挂方法,闲来广东麻将竟然真的是有辅助器(今日头条辅助)一、闲来广东麻将...
一分钟揭秘!海洋麻将辅助ai透... 您好,海洋麻将这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302】很多玩家在这款...
分享给玩家!老友福建麻将辅助a... 分享给玩家!老友福建麻将辅助ai透视挂工具,老友福建麻将其实存在有辅助(有辅助挂方式)1、老友福建麻...
一分钟了解!聚闲麻将辅助ai透... 一分钟了解!聚闲麻将辅助ai透视挂脚本,聚闲麻将一直真的有辅助器(确实有辅助挂)1、每一步都需要思考...
分享给玩家!上楚黄冈麻将辅助a... 分享给玩家!上楚黄冈麻将辅助ai透视挂攻略,上楚黄冈麻将切实真的是有外挂(有挂辅方法)1、该软件可以...
一分钟揭秘!山川休闲辅助ai透... 一分钟揭秘!山川休闲辅助ai透视挂软件,山川休闲好像是真的有辅助器(有辅助挂助手)1、不需要AI权限...
推荐攻略!中至上饶麻将辅助ai... 推荐攻略!中至上饶麻将辅助ai透视挂软件,中至上饶麻将果然真的是有透视器(有辅助挂细节)1、让任何用...
玩家必备教程!大唐撸麻雀辅助a... 玩家必备教程!大唐撸麻雀辅助ai透视挂技巧,大唐撸麻雀都是是真的有透视器(有辅助挂神器)暗藏猫腻,小...