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

相关内容

热门资讯

现有说明如下!德普之星透视免费... 现有说明如下!德普之星透视免费(透视)一贯真的是有挂(真是有挂开挂辅助脚本)-哔哩哔哩【无需打开直接...
近年来!pokernow辅助工... 近年来!pokernow辅助工具(透视)一直是有挂(有挂头条开挂辅助下载)-哔哩哔哩;无需打开直接搜...
现就发布提示!wepoker数... 现就发布提示!wepoker数据分析工具(透视)果然真的是有挂(存在有挂开挂辅助脚本)-哔哩哔哩1、...
今天下午!epoker免费透视... epoker免费透视脚本是一款专注玩家量身打造的游戏记牌类型软件,在epoker免费透视脚本这款游戏...
事发当天!hhpoker德州真... 事发当天!hhpoker德州真的假的(透视)其实真的是有挂(果真有挂开挂辅助安装)-哔哩哔哩>>您好...
一直以来!wepoker免费辅... 一直以来!wepoker免费辅助器(透视)果然是有挂的(今日头条开挂辅助神器)-哔哩哔哩【无需打开直...
突发!德普之星怎么设置埋牌(透... 突发!德普之星怎么设置埋牌(透视)原来是有挂(有挂技术开挂辅助辅助器)-哔哩哔哩德普之星怎么设置埋牌...
随着!aapoker怎么选牌(... 随着!aapoker怎么选牌(透视)一直确实有挂(有挂教程开挂辅助平台)-哔哩哔哩您好:aapoke...
此事引发网友热议!wpk有辅助... 此事引发网友热议!wpk有辅助吗(透视)一直确实有挂(有挂方法开挂辅助安装)-哔哩哔哩;无需打开直接...
今天上午!约局吧德州真的存在透... 约局吧德州真的存在透视吗是一款可以让一直输的玩家,快速成为一个“必胜”的ai辅助神器,有需要的用户可...