Angular8:在响应文本中引用的组件上运行ngOnInit或ngOnChanges
创始人
2024-10-22 15:32:07
0

在Angular 8中,你可以在响应文本中引用的组件上运行ngOnInit或ngOnChanges方法。下面是一个示例解决方法:

首先,创建一个名为“dynamic-component”的组件,它将在响应文本中引用:

dynamic-component.component.ts:

import { Component, Input, OnInit, OnChanges } from '@angular/core';

@Component({
  selector: 'app-dynamic-component',
  template: `
    
{{ message }}
` }) export class DynamicComponent implements OnInit, OnChanges { @Input() message: string; ngOnInit() { console.log('ngOnInit'); } ngOnChanges() { console.log('ngOnChanges'); } }

接下来,在父组件中,使用ComponentFactoryResolverViewContainerRef来动态创建和加载组件。在响应文本中引用的组件将作为动态加载的组件。

parent.component.ts:

import { Component, ViewChild, ViewContainerRef, ComponentFactoryResolver } from '@angular/core';
import { DynamicComponent } from './dynamic-component.component';

@Component({
  selector: 'app-parent',
  template: `
    
` }) export class ParentComponent { @ViewChild('dynamicComponentContainer', { read: ViewContainerRef }) dynamicComponentContainer: ViewContainerRef; constructor(private componentFactoryResolver: ComponentFactoryResolver) {} loadDynamicComponent(message: string) { this.dynamicComponentContainer.clear(); const componentFactory = this.componentFactoryResolver.resolveComponentFactory(DynamicComponent); const componentRef = this.dynamicComponentContainer.createComponent(componentFactory); componentRef.instance.message = message; } }

在上面的示例中,loadDynamicComponent方法用于加载动态组件。它首先清空dynamicComponentContainer容器,然后使用ComponentFactoryResolverViewContainerRef来创建并加载DynamicComponent

现在,你可以在父组件的模板中调用loadDynamicComponent方法并传递消息作为参数,以动态加载DynamicComponent

parent.component.html:


当点击“Load Dynamic Component”按钮时,loadDynamicComponent方法将被调用,动态加载DynamicComponent并传递消息作为参数。在DynamicComponent中,ngOnInitngOnChanges方法将被调用,并且消息将被显示在模板中。

希望这个示例可以帮助你解决问题!

相关内容

热门资讯

第八分钟方案!小南娱乐外g挂系... 第八分钟方案!小南娱乐外g挂系统,新海贝之城脚本(辅助)一直真的是有安装(哔哩哔哩);一、小南娱乐外...
第八分钟教材!衢州都莱有没有内... 第八分钟教材!衢州都莱有没有内部号,新九天辅助器(辅助)确实存在有插件(哔哩哔哩)1、第八分钟教材!...
第3分钟大纲!新玄龙斗牛卡牌,... 您好,三哥玩辅助器免费下载这款游戏可以开挂的,确实是有挂的,需要了解加去威信【485275054】很...
第十分钟窍要!福麻圈辅助器,新... 第十分钟窍要!福麻圈辅助器,新海贝辅助器(辅助)原来真的是有修改器(哔哩哔哩)1、实时新海贝辅助器透...
6分钟举措!一起宁德福鼎打炸辅... 6分钟举措!一起宁德福鼎打炸辅助,新西部挂透视辅助(辅助)总是是真的神器(哔哩哔哩)1、完成一起宁德...
2分钟步骤!神殿娱乐控制系统,... 2分钟步骤!神殿娱乐控制系统,新道游开挂辅助透视(辅助)竟然存在有平台(哔哩哔哩)1、新道游开挂辅助...
第五分钟指南书!胡乐辅助脚本,... 第五分钟指南书!胡乐辅助脚本,蛮王大厅脚本辅助(辅助)竟然是真的软件(哔哩哔哩)1、蛮王大厅脚本辅助...
一分钟绝活儿!欢乐对决脚本辅助... 一分钟绝活儿!欢乐对决脚本辅助器ios,新老夫子脚本免费下载(辅助)切实是有插件(哔哩哔哩)新老夫子...
一分钟积累!新圣游辅助软件在哪... 一分钟积累!新圣游辅助软件在哪下载,新海豚辅助工具(辅助)切实是有脚本(哔哩哔哩)1、点击下载安装,...
2分钟总结!传送五激k辅助靠谱... 2分钟总结!传送五激k辅助靠谱吗,三哥玩摆头挂(辅助)本来是真的脚本(哔哩哔哩)1、传送五激k辅助靠...