Angular 15懒加载组件:如何配置Input与Output属性
Angular懒加载组件配置Input与Output的方法
问题背景
已完成落地页高级搜索组件的懒加载改造,通过ViewContainerRef.createComponent动态创建组件,但不清楚如何为懒加载组件传递Input()数据以及捕获Output()事件。此前非懒加载时的写法为:
<app-material-advancesearch [searchkeywords]="searchkeywords" (notifyMaterialList)="refreshLists($event)"></app-material-advancesearch>
解决方案
1. 传递Input数据
通过createComponent方法会返回一个ComponentRef实例,直接访问该实例的instance属性即可设置组件的Input参数(Input本质是组件类的实例属性)。
修改后的loadAdvanceSearchForm方法:
async loadAdvanceSearchForm() { const { MaterialAdvanceSearchComponent } = await import( '../../material-advancesearch/material-advancesearch.component' ); this.formComponent.clear(); // 创建组件并获取组件引用 const componentRef = this.formComponent.createComponent(MaterialAdvanceSearchComponent); // 直接设置Input属性 componentRef.instance.searchkeywords = this.searchkeywords; }
2. 捕获Output事件
组件的Output()属性是EventEmitter类型,通过组件实例的instance属性获取该事件发射器后,调用subscribe方法即可监听事件。
如果组件可能被多次创建,建议保存订阅对象并在合适时机取消订阅,避免内存泄漏:
import { Subscription } from 'rxjs'; // 类内添加属性保存订阅对象 private notifySubscription?: Subscription; async loadAdvanceSearchForm() { const { MaterialAdvanceSearchComponent } = await import( '../../material-advancesearch/material-advancesearch.component' ); // 先取消之前的订阅(如果存在) this.notifySubscription?.unsubscribe(); this.formComponent.clear(); const componentRef = this.formComponent.createComponent(MaterialAdvanceSearchComponent); // 设置Input属性 componentRef.instance.searchkeywords = this.searchkeywords; // 订阅Output事件 this.notifySubscription = componentRef.instance.notifyMaterialList.subscribe((eventData) => { this.refreshLists(eventData); }); } // 组件销毁时取消订阅 ngOnDestroy() { this.notifySubscription?.unsubscribe(); }
额外说明
- 如果
searchkeywords是动态变化的,需要在数据更新时同步更新懒加载组件的属性,或者通过监听searchkeywords的变化来重新设置组件实例的属性。 - 若需要更灵活的组件通信,也可以考虑使用服务传递数据,但上述方法是最直接适配原有非懒加载逻辑的方式。
内容的提问来源于stack exchange,提问作者user2869612
相关产品推荐
相关产品推荐

