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

相关内容

热门资讯

开挂辅助工具"pok... 开挂辅助工具"pokerworld辅助器"开挂(透视)辅助插件(存在有挂)pokerworld辅助器...
开挂辅助神器"有哪些... 开挂辅助神器"有哪些免费的wpk辅助码"开挂(透视)辅助安装(真实有挂);无需打开直接搜索加(薇:1...
开挂辅助平台"wep... 《开挂辅助平台"wepoker免费辅助器"开挂(透视)辅助软件(有挂工具)》 wepoker免费辅助...
开挂辅助插件"佛手大... 开挂辅助插件"佛手大菠萝辅助"开挂(透视)辅助平台(有挂解惑);无需打开直接搜索微信(1367043...
开挂辅助插件"wep... 开挂辅助插件"wepoker辅助是真的吗"开挂(透视)辅助神器(讲解有挂) 了解更多开挂安装加(13...
开挂辅助插件"竞技联... 大家好,今天小编来为大家解答竞技联盟辅助插件这个问题咨询软件客服可以免费测试直接加微信(136704...
开挂辅助神器"竞技联... 开挂辅助神器"竞技联盟辅助插件"开挂(透视)辅助脚本(有挂解惑)>>您好:软件加136704302中...
开挂辅助工具"德普之... 开挂辅助工具"德普之星透视免费"开挂(透视)辅助软件(有挂技巧);无需打开直接搜索微信(136704...
开挂辅助安装"wep... 开挂辅助安装"wepokerplus到底是挂了吗"开挂(透视)辅助平台(真的有挂);无需打开直接搜索...
开挂辅助脚本"德州局... 您好:这款德州局怎么透视游戏是可以开挂的,确实是有挂的,很多玩家在这款德州局怎么透视游戏中打牌都会发...