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

相关内容

热门资讯

脚本透视!hhpoker真的假... 脚本透视!hhpoker真的假的,hhpoker德州挂真的有吗(透视)确实真的是有器(哔哩哔哩)1、...
透视数据!hh poker软件... 透视数据!hh poker软件,微乐陕西三代自建房挂,解迷脚本(有挂详情)-哔哩哔哩1、hh pok...
备受关注的!wepoker怎么... 备受关注的!wepoker怎么看牌型,微乐小程序辅助开发,解迷脚本(有挂方式)-哔哩哔哩1)wepo...
透视解迷!wepoker有透视... 透视解迷!wepoker有透视底牌吗,wepoker怎么挂底牌(透视)总是是有神器(哔哩哔哩)1、玩...
透视线上!pokemmo脚本最... 透视线上!pokemmo脚本最新版,微信小程序微乐挂如何获取,揭露脚本(有挂秘籍)-哔哩哔哩1、全新...
透视开挂!aapoker万能辅... 透视开挂!aapoker万能辅助器,aapoker辅助器怎么用(透视)果然真的是有方法(哔哩哔哩)该...
做出回应!hh poker辅助... 做出回应!hh poker辅助有用吗,微乐家乡app下载,了解脚本(有挂细节)-哔哩哔哩1)hh p...
透视曝光!德普辅助软件,如何下... 透视曝光!德普辅助软件,如何下载德普之星辅助软件(透视)一直是有脚本(哔哩哔哩)1、每一步都需要思考...
透视攻略!pokemmo辅助器... 透视攻略!pokemmo辅助器手机版下载,微乐自建房辅助神器怎么安装,教你脚本(有挂详情)-哔哩哔哩...
脚本有挂!微扑克微乐辅助,wp... 脚本有挂!微扑克微乐辅助,wpk透视辅助方法(透视)总是有攻略(哔哩哔哩)1、脚本有挂!微扑克微乐辅...