지시문에서 내 보낸 이벤트를 수동으로 구독하려고합니다. 이것은 설계 상 내 응용 프로그램의 여러 구성 요소에서 사용할 수 있어야합니다. 순간 구조는 다음과 같습니다Angular2 : rxjs Angular2 자식 - 부모 구성 요소 상호 작용
나중에 개발에@NgModule({
imports: [ BrowserModule, HttpModule, JsonpModule, RouterModule.forRoot(appRoutes) ],
declarations: [ AppComponent, FooComponent, BarComponent, ParentComponent, DraggableDirective ],
bootstrap: [ AppComponent ]
})
, 다른 부모 구성 요소를 드래그 지시를 듣고하고 자신을 구현합니다
AppComponent
Draggable.Directive (uses an attribute of a DOM element to control the behaviour)
(and then, via routing)
Parent1 Component
Child1 Component
Child2 Component
app.module은 다음과 같습니다 논리.
아무 어린이 구성 요소도 Draggable Directive에서 아무 것도하지 않고 있음을 알고 있습니다 (또는 신경 써야 함). 상위 구성 요소가 있어야합니다.
import { Directive, ElementRef, Renderer, HostListener, AfterViewInit } from '@angular/core';
import {Subject} from 'rxjs/Rx';
@Directive({
selector: '[draggable], [data-draggable]'
})
export class DraggableDirective implements AfterViewInit {
public droppedOn = new Subject();
//... at some point this method is envoked
couldDrop():void {
if (this.dElem) {
let _attr = this.dElem.dataset.indexed;
console.log('emitting', _attr);
this.droppedOn.next(_attr);
}
}
}
나는 올바른으로 "발광"콘솔 로깅을 얻을 : 그래서, 부모 구성 요소에서 : 다른 권장 여기
import { Component, OnInit, ViewChild } from '@angular/core';
import { DraggableDirective } from './draggable.directive';
import { FooComponent } from './foo.component';
import { BarComponent } from './bar.component';
@Component({
selector: 'parent-view',
templateUrl: './parent.component.html',
providers: [DraggableDirective],
moduleId: module.id
})
export class ParentComponent implements OnInit {
@ViewChild('foo') fooC:FooComponent;
@ViewChild('bar') barC:BarComponent;
constructor(private draggable:DraggableDirective){
draggable.droppedOn.subscribe(event => {
console.log('listening', event);
})
}
ngOnInit(): void {
// updated
// child view components
this.fooC.fooInit();
}
그리고 주제와하지 EventEmitter를 사용하여 지시입니다 값. 콘솔의 상위 구성 요소에서 "수신 대기"를하지 않습니다. 여기서 내가 뭘 잘못하고 있니?
좋아, 지금까지 그렇게 좋았어. 하위 구성 요소에서 Subject()를 구독하고 부모 구성 요소로 전달해야합니까? – pop
@pop 아니요,'@ ViewChildren' 주석과 상위 컴포넌트에서 Observable 자체 인'QueryList'를 사용하여 모든 DraggableDirective 지시어 목록을 업데이트합니다. 거기에 각자의'dropOn' 속성에 접근하여 그곳에 가입 할 수 있습니다. – martin
http://stackoverflow.com/questions/32693061/angular-2-typescript-get-hold-of-an-element-in-the-template/35209681#35209681 – martin