[英]Angular2,How to broadcast event from parent component to child directive?
在Angular1中,它具有$scope.braodcast
,而EventEmitter
中的EventEmitter只能將事件從子級發送到父級。 那么如何將事件廣播到子指令?
這是我的孩子指令
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
}
}
這是我的父組件
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>
有很多方法可以做到這一點。 但是我會選擇最少的配置。
ParentComponent
import {ViewChild} from '@angular/core';
export class DetailListComponent implements OnInit {
ViewChild('svgLine') vc:svgLine;
// you can have an access over svgLine diretive
clickItem() {
// broadcast the event here
this.vc.printf('Angular2');
// Not sure if it can call ngOnInit as haven't tested it ever.
// But you can try calling and see if works.
// this.vc.onInit() something
}
}
svgLineDirective
export class HighlightDirective implements OnInit {
ngOnInit(): void {
// receive the event
}
printf(message:string){
alert(message);
}
}
對於孩子到父母,可以將輸出 api與EventEmitter api一起使用。 有成千上萬的示例可供使用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.