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

相关内容

热门资讯

7分钟详情!心悦游戏万能透视辅... 7分钟详情!心悦游戏万能透视辅助器免费,四川途游破解安装包(切实有挂)-哔哩哔哩1、心悦游戏万能透视...
七分钟详细!哈局十三张通用辅助... 七分钟详细!哈局十三张通用辅助,三哥玩辅助器(原来是有挂)-哔哩哔哩1、哈局十三张通用辅助系统规律教...
4分钟专业!大巴杭州辅助,约战... 4分钟专业!大巴杭州辅助,约战平台辅助(好像真的有挂)-哔哩哔哩约战平台辅助辅助器中分为三种模型:约...
三分钟解谜!开心泉州免费辅助器... 三分钟解谜!开心泉州免费辅助器,潮汕汇app辅助(其实是真的挂)-哔哩哔哩1、玩家可以在开心泉州免费...
1分钟分享!爱玩联盟辅助软件,... 1分钟分享!爱玩联盟辅助软件,新518互游插件(好像是真的挂)-哔哩哔哩1、金币登录送、破产送、升级...
第3分钟揭露!欢聚水鱼科技辅助... 第3分钟揭露!欢聚水鱼科技辅助下载,新青鸟必胜(真是真的有挂)-哔哩哔哩1、点击下载安装,欢聚水鱼科...
第1分钟普及!逍遥辅助器大全官... 第1分钟普及!逍遥辅助器大全官网,九九山城万州版辅助(原来是有挂)-哔哩哔哩第1分钟普及!逍遥辅助器...
第2分钟必备!新道游正版辅助,... 第2分钟必备!新道游正版辅助,途游手游辅助(果然是有挂)-哔哩哔哩1、第2分钟必备!新道游正版辅助,...
第7分钟推荐!老友内蒙麻将有挂... 第7分钟推荐!老友内蒙麻将有挂吗,混沌休闲有没有挂(一直是有挂)-哔哩哔哩1、起透看视 老友内蒙麻将...
五分钟解谜!广东雀神智能插件官... 五分钟解谜!广东雀神智能插件官网,海南骨牌辅助器免费(确实真的有挂)-哔哩哔哩1、操作简单,无需注册...