2017-02-21 2 views
0

Angular1의 경우 $scope.braodcast이고 Angular2의 경우 EventEmitter은 자식에서 부모로 만 이벤트를 방출 할 수 있습니다. 그렇다면이 이벤트를 아동 지침에 어떻게 방송 할 수 있습니까?Angular2, 부모 구성 요소에서 하위 구성 요소로 이벤트를 브로드 캐스트하는 방법은 무엇입니까?

이 내 아이 지시어

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> 

답변

0

여러 가지 방법이 있습니다. 하지만 최소 구성으로 갈 것입니다.

부모에게 자녀를 들어, EventEmitter API를 출력 API를 사용할 수 있습니다

export class HighlightDirective implements OnInit {  
    ngOnInit(): void { 
     // receive the event 
    } 

    printf(message:string){ 
     alert(message); 
    } 
} 

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. 수천 가지의 예제를 사용할 수 있습니다.

+0

angular1의 $ attrs.id와 같이 지시문에서 id의 지시어를 어떻게 얻을 수 있습니까? –

+0

지시어에 ElementRef를 삽입하여 장식하는 요소에 액세스합니다. –

관련 문제