我正在尝试将动态组件(在运行时创建(和EventEmitter概念访问Angular 8中的父组件中的子组件的数据。
>我的计划是创建一个功能,用户可以动态地添加元素(例如仪表板上的卡片(并同样删除它们。在这种情况下,创建的卡具有"删除"按钮。此删除按钮应该将信息传播到父组件,可以从包含动态创建的组件的数组中删除子组件。
我在本教程中从角文档中读到,我需要创建一个指令。现在,我已经有了Sut(我认为(,指令位于父母和子女组件之间,而我不知道如何正确删除事件以从上述数组中删除子组件。
指令
@Directive({
selector: '[appCards]'
})
export class CardDirective {
constructor(public viewContainerRef: ViewContainerRef) {
}
@Output() directiveDelete = new EventEmitter<any>();
}
父级
card-banner.component.ts
@Component({
selector: 'app-card-banner',
templateUrl: './card-banner.component.html',
styleUrls: ['./card-banner.component.scss']
})
export class CardBannerComponent implements OnInit, OnDestroy {
constructor(private componentFactoryResolver: ComponentFactoryResolver) { }
@Input() cards: CardItem[];
@ViewChild(CardDirective) appCards: CardDirective;
loadCards() {
const viewContainerRef = this.appCards.viewContainerRef;
viewContainerRef.clear();
for (const card of this.cards) {
const componentFactory =
this.componentFactoryResolver.resolveComponentFactory(card.component);
const componentRef = viewContainerRef.createComponent(componentFactory);
(componentRef.instance as CardContentComponent).data = card.data;
}
}
addCard() {
this.cards.push(new CardItem(CardContentComponent, {name: 'Card Dynamisch'}));
this.loadCards();
}
removeLastCard() {
this.cards.pop();
this.loadCards();
}
onDelete(deleteBool: any) {
console.log(deleteBool);
console.log('delete in card-banner');
}
ngOnInit() {this.loadCards();
}
ngOnDestroy(): void {
}
}
card-banner.component.html
<button (click)="addCard()" class="btn">Add Card</button>
<button (click)="removeLastCard()" class="btn">Remove Card</button>
<div style="margin: auto;">
<ng-template appCards (directiveDelete)="onDelete($event)"></ng-template>
</div>
儿童组件
card-content.component.ts
@Component({
selector: 'app-card',
templateUrl: './card-content.component.html',
styleUrls: ['./card-content.component.scss']
})
export class CardContentComponent implements CardInterfaceComponent {
@Input() data: any;
@Output() delete = new EventEmitter<any>();
removeCard() {
this.delete.emit(true);
console.log('delete card: ' + this.data.name);
}
}
card-content.component.html
<div >
<div style="display: inline;">{{data.name}} <button (click)="removeCard()" class="btn">Delete</button></div>
</div>
我也有一个卡服务,一个卡 - 界面和一个纸牌项目,但我认为它们在这种情况下没有影响,所以我没有发布它们。如果它们是必要的,我可以添加它们。
因此,我的问题是,父组件未从子comoponent接收删除消息,因此无法删除卡。
我希望有人可以帮助我理解,在这种情况下,信息丢失的地方以及我应该如何使用eventemitter。
预先感谢您!
在动态创建它之后订阅组件事件:
loadCards() {
const viewContainerRef = this.appCards.viewContainerRef;
viewContainerRef.clear();
for (const card of this.cards) {
const componentFactory = this.componentFactoryResolver.resolveComponentFactory(card.component);
const componentRef = viewContainerRef.createComponent<CardContentComponent>(componentFactory);
componentRef.instance.data = card.data;
componentRef.instance.delete.subscribe(() => {
// handle delete logic
});
}
}