我想創建Angular2可選列表:Angular 2主從指令通信。國米指令通信
import {Directive, ElementRef, HostListener, Input, Output, EventEmitter} from "@angular/core";
@Directive({selector: 'li'})
export class ListItem {
@Input() private selectableItem: any;
@Output('selectedEvent') private selectedEvent: EventEmitter<any> = new EventEmitter<any>();
constructor(private hostElement: ElementRef) {
}
@HostListener('click', ['$event'])
private toggleSelected(event: MouseEvent): void {
this.hostElement.nativeElement.classList.toggle('selected');
this.selectedEvent.emit(this.selectableItem);
}
}
@Directive({selector: '[selectableList]'})
export class SelectableListDirective {
constructor(private hostElement: ElementRef) {
}
@HostListener('selectedEvent', ['$event'])
private liWasClicked(event): void {
console.log(event);
}
}
而且我嘗試使用它,像這樣:
<ul selectableList>
<li *ngFor="let item of items" [selectableItem]="item">
<span>{{item}}</span>
</li>
</ul>
Plunker:https://plnkr.co/edit/umIE6yZwjyGGvJdYe7VS?p=preview
問題是:liWasClicked永遠不會被點擊!
我在這裏遇到了同樣的問題,我無法使用子指令與父指令進行通信。任何人都可以幫忙 – soywod
@soywod如果你的指令有模板,事件有效,但在我的情況下,它們不會,所以事實並非如此。 – dalvarezmartinez1