在Angular1中,它具有 $scope.braodcast
. 而Angular2中的 EventEmitter
只能从子到父发出一个事件 . 那么如何将该事件广播到子指令呢?
this is my child directive
import { Directive, ElementRef, Input, Output, OnInit } from '@angular/core';
import { EventEmitter } from '@angular/core';
@Directive({
selector: '[svgLine]'
})
export class HighlightDirective implements OnInit {
message: string;
constructor(
private el: ElementRef,
) {}
@Input() svgLineClientWidth: number;
@Input() svgLineClientHeight: number;
@Input() svgToClientWidth: number;
@Input() svgToClientHeight: number;
@Input() svgLineFromId: number;
@Input() svgLineToId: number;
ngOnInit(): void {
// receive the event
}
}
and this is my parent component
import { Component, OnInit, EventEmitter, Output } from '@angular/core';
import { Tools } from '../class/tools'
import { DetailListService } from './detail-list.service';
@Component({
// moduleId使用于CommonJs
moduleId : module.id,
selector : 'detail-list',
templateUrl : './detail-list.component.html',
styleUrls: ['./detail-list.component.css'],
})
export class DetailListComponent implements OnInit {
constructor(
private detailListService : DetailListService,
) {}
clickItem() {
// broadcast the event here
}
}
detail-list.component.html
<svg class="svg--position">
<g *ngFor="let item of model.data">
<g pointer-events="painted"
svgLine
*ngFor="let to of item.to"
[svgLineClientWidth]="item.clientWidth"
[svgLineClientHeight]="item.clientHeight"
[svgToClientWidth]="to.clientWidth"
[svgToClientHeight]="to.clientHeight"
[svgLineFromId]="item.id"
[svgLineToId]="to.id"
id="{{item.title}}{{item.id}}{{to.id}}"
>
</g>
</g>
</svg>
1 回答
有很多方法可以做到这一点 . 但我会采用最低配置 .
ParentComponent
svgLineDirective
对于孩子到父母,您可以使用 output api和 EventEmitter api . 有数以千计的例子可供选择 .