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

相关内容

热门资讯

黑科技教程!wpk俱乐部怎么盈... 黑科技教程!wpk俱乐部怎么盈利(智能ai)太坑了是有挂(大神讲解黑科技插件)-哔哩哔哩1、首先打开...
黑科技神器!德州AI智能辅助机... 黑科技神器!德州AI智能辅助机器人,智星德州菠萝,AI教程(有挂教程)-哔哩哔哩1、构建自己的微扑克...
黑科技有挂!来玩app德州安卓... 黑科技有挂!来玩app德州安卓有用吗(透明挂)总是真的有挂(有挂线上)-哔哩哔哩这是由厦门游乐互动科...
黑科技新版!线上wpk德州ai... 黑科技新版!线上wpk德州ai机器人(ai代打)太坑了真的有挂(黑科技教程黑科技教程)-哔哩哔哩1、...
黑科技ai!aapoker透视... 黑科技ai!aapoker透视辅助,wepoke有辅助挂,攻略方法(有挂详情)-哔哩哔哩是一款可以让...
黑科技透明挂挂!德州ai辅助工... 黑科技透明挂挂!德州ai辅助工具购买(透明挂)原本真的有挂(有挂下载)-哔哩哔哩;人气非常高,ai更...
黑科技讲解!wopoker辅助... 黑科技讲解!wopoker辅助真的假的(黑科技ai)太坑了真的有挂(AA德州教程黑科技插件)-哔哩哔...
黑科技辅助!aapoker外挂... 黑科技辅助!aapoker外挂,德扑之星系统发牌机制,教你教程(有挂规律)-哔哩哔哩1、德扑之星系统...
黑科技安装!wpk发牌机制(a... 黑科技安装!wpk发牌机制(ai代打)确实是有挂(有挂透明挂)-哔哩哔哩;玩家必备必赢加哟《1367...
黑科技最新!wpk微扑克外挂事... 黑科技最新!wpk微扑克外挂事件(智能ai)太坑了存在有挂(新版2025教程黑科技脚本)-哔哩哔哩1...