2017-08-29 43 views
-1

我是Angular的新手,並且試圖將子組件中的數組傳遞給父組件。在子組件,我有以下幾點:如何將路由的孩子的@Output值轉換爲父組件Angular 4

export class AoRSummaryComponent implements OnInit, AfterViewInit, OnDestroy { 
@Output() fooDetails: EventEmitter<any> = new EventEmitter(); 
... 
//then the code that builds the array (this.detailsObj.aorDetails) 
... 
this.fooDetails.emit(this.detailsObj.aorDetails); 

我的問題是,我該怎麼包括父組件的HTML,才能在語句中的* ngFor =「fooDetails的細節讓」使用fooDetails?我似乎無法使用<child-component-selector></child-component-selector>語句,因爲我們使用<router-outlet>加載子組件。任何幫助將非常感激。

+0

找到你解決這個問題? –

回答

0

如果通過router-outlet指令將所謂的「子」組件呈現在它的「父」組件中,那麼您不會真正擁有父子關係。這種情況的典型解決方案是在相關組件之間共享服務實例。關於這個話題

@Injectable() 
export class FooService{ 
    private _value$ = new BehaviorSubject<number>(42); 
    ctor(){} 

    get value$(){ 
    return this._value$.asObservable(); 
    } 

    pushData(v: number){ 
    this._value$.next(v); 
    } 
} 

export class ParentComponent implements OnInit { 
value$: Observable<number>; 
ctor(private _service: FooService){} 

ngOnInit(){ 
    this.value$ = this._service.value$(); 
} 

//Add ngOnDestroy in case that you manually subscribe to value$ 
} 

export class ChildComponent{ 
    ctor(private _service: FooService){} 

    triggerEvent(v: number){ 
    this._service.pushData(v); 
    // this replaces emitter.emit(v) 
    } 
} 

更多信息可以在in the docs

相關問題