首页 文章

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

提问于
浏览
0

在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 回答

  • 1

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

    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);
      }
    }
    

    对于孩子到父母,您可以使用 output api和 EventEmitter api . 有数以千计的例子可供选择 .

相关问题