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

相关内容

热门资讯

一分钟教你!wepoker私人... 一分钟教你!wepoker私人辅助器(辅助挂)竟然是有挂(有挂辅助)1、超多福利:超高返利,海量正版...
玩家实测!wepoker正确养... 玩家实测!wepoker正确养号方法(辅助挂)一贯真的有挂(有挂详情)进入游戏-大厅左侧-新手福利-...
我来教大家!约局吧开挂神器是真... 我来教大家!约局吧开挂神器是真的吗(辅助挂)一贯存在有挂(有挂详细)1、约局吧开挂神器是真的吗脚本辅...
盘点一款!拱趴大菠萝万能挂图解... 盘点一款!拱趴大菠萝万能挂图解(辅助挂)确实是真的有挂(有挂详情)1、下载好拱趴大菠萝万能挂图解正确...
玩家必看科普!wepoker手... 玩家必看科普!wepoker手机插件(辅助挂)一贯是有挂(果真有挂)1)wepoker手机插件辅助插...
一分钟揭秘!hh poker有... 一分钟揭秘!hh poker有没有辅助软件!果然真的是有辅助教程(有挂总结);1、hh poker有...
总算清楚!八闽掌上辅助软件!都... 总算清楚!八闽掌上辅助软件!都是存在有辅助挂(有挂规律)1、八闽掌上辅助软件公共底牌简单,八闽掌上辅...
一分钟揭秘!凑一桌游戏插件!其... 一分钟揭秘!凑一桌游戏插件!其实是真的有辅助插件(讲解有挂)所有人都在同一条线上,像星星一样排成一排...
每日必看推荐!卡五星辅助神器!... 每日必看推荐!卡五星辅助神器!总是存在有辅助攻略(有挂辅助)1、卡五星辅助神器公共底牌简单,卡五星辅...
教程攻略!卡五星辅助器!确实是... 教程攻略!卡五星辅助器!确实是真的有辅助攻略(讲解有挂)1、用户打开应用后不用登录就可以直接使用,点...