Angular2,如何将事件从父组件广播到子指令?

时间:2017-02-21 03:16:11

标签: angular angular2-directives angular2-components

在Angular1中,它具有$scope.braodcast。而Angular2中的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
      }
    }

细节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 个答案:

答案 0 :(得分:1)

有很多方法可以做到这一点。但是我会采用最低配置。

<强>为父级

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一起使用。有数以千计的例子可供选择。