我创建了两个窗口小部件组件,例如,数据和图表窗口小部件,这些窗口小部件由另一个名为Card组件的组件进行转换。在Card组件中,我使用了一个常用的关闭按钮,这样我就可以默认使用每个小部件中的关闭按钮。动态创建数据和图表小部件并保存在数组中,最后组件在html模板上呈现。 现在,我想通过单击每个小部件上的关闭按钮来删除阵列中的组件。我尝试了以下方式,
CardComponent.ts
import { Component, Input, Output, EventEmitter } from '@angular/core';
import {WidgetComponent} from './widget.component';
@Component({
selector: 'card',
templateUrl: 'card.component.html',
})
export class CardComponent {
@Input()
public header: string = 'this is header';
@Input()
public footer: string = 'this is footer';
@Output() closeWidget = new EventEmitter();
close(){
console.log('Card close');
this.closeWidget.emit();
}
}
CardComponent.html
<div class="card" style="border: 1px solid #d0d0d0;">
<div class="card-header">
{{ header }}
<a (click)="close()" class="btn btn-primary">Close</a>
</div>
<ng-content></ng-content>
<div class="card-footer">
{{ footer }}
</div>
</div>
图表-widget.component.ts
@Component({
selector: 'chart-widget',
templateUrl: './app/chart-widget.component.html',
providers: [{provide: WidgetComponent, useExisting: forwardRef(() => ChartWidget) }]
})
export class ChartWidget extends WidgetComponent implements OnInit {
}
图表-widget.component.html
<card header="Chart Panel" footer="Footer here" class="ui-toolbar-group-
right">
<div class="card-block">
<h4 class="card-title">Chart Card</h4>
<p class="card-text">Chart showing here</p>
</div>
</card>
AppComponent.ts
@Component({
selector: 'app-root',
templateUrl: './app/app.component.html',
styleUrls: ['./app/app.component.css'],
entryComponents: [ChartWidget, DataWidget],
})
export class AppComponent {
private elements: Array<{ view: ViewRef, component: WidgetComponent}>=[];
private WidgetClasses = {
'ChartWidget': ChartWidget,
'DataWidget': DataWidget
}
@ViewChild(DynamicComponent) dynamicComponent:DynamicComponent;
addComponent(widget: string ): void{
let component = this.dynamicComponent.addComponent(this.WidgetClasses[widget]);
let view: ViewRef = this.dynamicComponent.container.detach(0);
this.elements.push({view,component});
this.dynamicComponent.resetContainer();
}
onWidgetDelete(element: any){
console.log('Call Delete called');
var index = this.elements.findIndex((elt) => (elt===element));
if (index !== -1) {
this.elements.splice(index, 1);
}
}
}
app.component.html
<button (click)="addComponent('ChartWidget')">Add ChartWidget</button>
<button (click)="addComponent('DataWidget')">Add DataWidget</button>
<dynamic-component [hidden]="true" ></dynamic-component>
<hr>
Dynamic Components
<hr>
<widget *ngFor="let item of elements" (closeWidget)="onWidgetDelete(item)">
<ng-container *view="item.view" ></ng-container>
</widget>
我在控制台上收到click事件消息,但EventEmitter不起作用。如何通过单击关闭按钮删除组件? 这是我的Plunker https://plnkr.co/edit/tFmcpre6FHysJ1uUFPp5?p=preview