【发布时间】:2020-03-01 05:37:03
【问题描述】:
我是 Angular 的新手。我有一个按钮,每次单击它时,它都会动态创建一个组件。我需要每个组件都有一个按钮或可以专门破坏该组件的东西。我在动态组件中有一个功能,当我点击它时,该组件必须关闭,但我不知道如何将它传递给打字稿文件的功能。请帮助我。
app.component.ts
import { Component, OnInit, ComponentFactoryResolver, ViewChild, Input,ComponentRef,ViewContainerRef } from '@angular/core';
import {ChatService} from "./services/chat.service";
import {Mensaje} from "./models/mensaje";
import {ConversacionComponent} from "./components/conversacion/conversacion.component";
import {ConversacionDirective} from "./components/conversacion/conversacion.directive";
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
providers:[ChatService]
})
export class AppComponent {
@ViewChild(ConversacionDirective, {static: true}) eldinamico: ConversacionDirective;
title = 'chat';
constructor(private cfr: ComponentFactoryResolver){ }
ngOnInit() { }
componenteDinamico(mensaje: string) {
const cf = this.cfr.resolveComponentFactory(ConversacionComponent);
const vcr = this.eldinamico.viewContainerRef;
vcr.createComponent(cf, 0);
}
}
conversacion.directive.ts
import { Directive, ViewContainerRef } from '@angular/core';
@Directive({
selector: '[appConversacionDinamica]'
})
export class ConversacionDirective {
constructor(public viewContainerRef: ViewContainerRef) { }
}
app.component.html
<input type="text" #mensaje><br/>
<button (click)="componenteDinamico(mensaje.value)"> Crear Componente </button>
<br/>
<div class="orden">
<ng-template appConversacionDinamica></ng-template>
</div>
conversacion.component.html
<button (click)="removeObject()">delete me</button>
<div>
this is a component dynamically
</div>
conversacion.component.ts
import {Component, Input, OnInit, Output, EventEmitter,ViewChild,ElementRef,ComponentRef} from '@angular/core';
@Component({
selector: 'app-conversacion',
templateUrl: './conversacion.component.html',
styleUrls: ['./conversacion.component.css']
})
export class ConversacionComponent implements OnInit {
mensaje: string;
vcr:any;
constructor() {}
ngOnInit() {}
removeObject(){
this.vcr.destroy();
}
}
【问题讨论】: