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

相关内容

热门资讯

透视了解!wepokerplu... 透视了解!wepokerplus到底是挂了吗(透视)总是真的是有辅助下载(有挂总结)-哔哩哔哩1.w...
透视透视挂!pokemmo手机... 透视透视挂!pokemmo手机版修改器(透视)其实存在有辅助插件(有挂规律)-哔哩哔哩1、透视透视挂...
透视app!pokemmo内置... 透视app!pokemmo内置修改器(透视)原来真的有辅助软件(真是有挂)-哔哩哔哩1、金币登录送、...
透视辅助!wepoker开脚本... 透视辅助!wepoker开脚本视频(透视)一贯有辅助软件(了解有挂)-哔哩哔哩1、全新机制【wepo...
透视美元局!wpk安卓下载辅助... 透视美元局!wpk安卓下载辅助(透视)总是真的有辅助工具(有挂秘诀)-哔哩哔哩1、wpk安卓下载辅助...
透视透视!拱趴大菠萝辅助神器(... 透视透视!拱趴大菠萝辅助神器(透视)一贯真的有辅助神器(有挂透视)-哔哩哔哩1、拱趴大菠萝辅助神器透...
透视挂透视!wepoker轻量... 透视挂透视!wepoker轻量版透视(透视)果然有辅助插件(有挂分享)-哔哩哔哩1、透视挂透视!we...
截至发稿!智星德州插件最新版本... 截至发稿!智星德州插件最新版本更新内容详解(透视)其实存在有辅助插件(有挂方法)-哔哩哔哩1)智星德...
来临!sohoo竞技联盟辅助器... 来临!sohoo竞技联盟辅助器(透视)竟然是真的辅助app(有挂方针)-哔哩哔哩1、任何sohoo竞...
近年来!德州来玩辅助器(透视)... 近年来!德州来玩辅助器(透视)好像存在有辅助下载(今日头条)-哔哩哔哩1、完成德州来玩辅助器辅助器v...