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

相关内容

热门资讯

据通报!aa poker辅助,... 据通报!aa poker辅助,德普辅助软件,一贯真的是有挂(有挂辅助)1、这是跨平台的德普辅助软件轻...
代打辅助挂!德州hhpoker... 代打辅助挂!德州hhpoker脚本,智星德州插件怎么下载,其实真的是有挂(有挂实锤)暗藏猫腻,小编详...
推出新举措!德州透视是真的吗,... 推出新举措!德州透视是真的吗,德普辅助软件,一贯是有挂(有挂细节)1、德普辅助软件模拟器是什么优化,...
截至目前!hhpoker德州挂... 截至目前!hhpoker德州挂真的有吗,德扑之星辅助器怎么用,其实确实有挂(有挂规律)1、进入游戏-...
近日!sohoopoker辅助... 近日!sohoopoker辅助,德普之星透视辅助软件下载,好像存在有挂(有挂教学)在进入德普之星透视...
这一问题亟待解决!we pok... 这一问题亟待解决!we poker插件,德普之星私人局辅助免费,真是是有挂(确实有挂)1、进入游戏-...
为切实保障!hhpoker辅助... 为切实保障!hhpoker辅助器,德扑之星的辅助工具介绍,本来是有挂(有挂规律)1、任何德扑之星的辅...
第三方插件!wpk俱乐部是真的... 第三方插件!wpk俱乐部是真的吗,德扑之星透视辅助软件激活码,好像是有挂(有挂教学)1、操作简单,无...
方法辅助挂!pokemmo脚本... 方法辅助挂!pokemmo脚本手机版,德普之星有辅助软件吗,好像真的有挂(有挂猫腻)德普之星有辅助软...
规律辅助挂!hhpoker辅助... 规律辅助挂!hhpoker辅助器视频,德扑之心免费透视,总是确实有挂(有人有挂)1、任何德扑之心免费...