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

相关内容

热门资讯

一直以来!aapoker怎么选... 一直以来!aapoker怎么选牌(透视)心悦填大坑辅助器(其实是真的辅助app)-哔哩哔哩;心悦填大...
透视能赢!hhpoker怎么防... 透视能赢!hhpoker怎么防作必弊(透视)和和营口麻将辅助(其实真的是有辅助插件)-哔哩哔哩运和和...
据悉!wpk俱乐部有没有辅助(... 据悉!wpk俱乐部有没有辅助(透视)微乐小程序辅助脚本平台(切实有辅助安装)-哔哩哔哩1、全新机制【...
一直以来!佛手在线大菠萝辅助(... 一直以来!佛手在线大菠萝辅助(透视)九游破解版真的假的(果然是真的辅助app)-哔哩哔哩1、九游破解...
透视脚本!wpk辅助器(透视)... 透视脚本!wpk辅助器(透视)多乐跑得快辅助器(其实是真的辅助平台)-哔哩哔哩该软件可以轻松地帮助玩...
在玩家背景下!xpoker辅助... 在玩家背景下!xpoker辅助控制(透视)789大菠萝攻略(确实是有辅助辅助器)-哔哩哔哩789大菠...
透视数据!wepoker插件程... 透视数据!wepoker插件程序激活码(透视)南丰数刀脚本(一贯存在有辅助app)-哔哩哔哩1.we...
据报道!hhpoker为什么一... 据报道!hhpoker为什么一直输(透视)传送屋激k怎么开挂(本来存在有辅助软件)-哔哩哔哩一、传送...
透视中牌率!德普之星透视辅助软... 透视中牌率!德普之星透视辅助软件(透视)微乐广西小程序开挂(果然真的有辅助插件)-哔哩哔哩1、微乐广...
透视安卓版!aapoker透视... 透视安卓版!aapoker透视方法(透视)广西来趣app有挂吗(果然真的是有辅助app)-哔哩哔哩广...