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

相关内容

热门资讯

黑科技能赢!云扑克辅助器苹果(... 黑科技能赢!云扑克辅助器苹果(微扑克ai机器人)本然真的是有挂(有挂技巧)-哔哩哔哩1.微扑克ai机...
黑科技神器!聚星扑克这个平台靠... 黑科技神器!聚星扑克这个平台靠谱(wepoke辅助插件)从前真的是有挂(真的有挂)-哔哩哔哩是一款可...
黑科技挂!微扑克数据采集(aa... 黑科技挂!微扑克数据采集(aapoker发牌机制)往昔有挂(真实有挂)-哔哩哔哩1、打开德州poke...
黑科技美元局!云扑克有辅助软件... 黑科技美元局!云扑克有辅助软件(德扑ai智能系统)果然是有挂(有挂方式)-哔哩哔哩1、不需要AI权限...
黑科技插件!红龙扑克ai(wp... 黑科技插件!红龙扑克ai(wpk ai辅助)先前是有挂(真实有挂)-哔哩哔哩;一、wpk ai辅助有...
黑科技辅助!wpk有赢的(德州... 黑科技辅助!wpk有赢的(德州ai辅助神器软件)最初真的是有挂(有挂分享)-哔哩哔哩1、任何德州ai...
黑科技能赢!微扑克辅牌器(德州... 1、黑科技能赢!微扑克辅牌器(德州ai辅助神器软件)都是存在有挂(有挂技巧)-哔哩哔哩;代表性(透视...
黑科技美元局!扑克时间有后台控... 黑科技美元局!扑克时间有后台控制(wpk ai辅助)一直存在有挂(有人有挂)-哔哩哔哩1、每一步都需...
黑科技私人局!德扑ai工具(德... 黑科技私人局!德扑ai工具(德州ai辅助)其实有挂(真的有挂)-哔哩哔哩1、不需要AI权限,帮助你快...
黑科技计算!智星德州菠萝安全(... 黑科技计算!智星德州菠萝安全(德州ai软件购买)本来是真的有挂(有挂详情)-哔哩哔哩是一款可以让一直...