2017-10-04 30 views
0

我試圖從具有與子組件關聯的(更改)事件的選擇輸入向父元素傳遞輸入值。 希望變量在每次更新子組件變量時都得到更新。當變量基於使用Angular的更改事件更改時,將變量從子組件傳遞到父組件

我的問題與Question不同,因爲我在變化事件上發生了變化,每次變量變化時都需要更新。

我能夠使用ViewChild和AfterViewInit解決這個問題,但在控制檯中出現錯誤:ExpressionChangedAfterItHasBeenCheckedError:檢查後表達式已更改。先前的值:'未定義'。當前值:'測試'。

想象一下,這樣做有一個簡單的方法。請記住,我對Angular仍然很陌生。

輔元件模板:

<form> 
    <div class="form-group"> 
    <label for="Master-Products">Select Master Product</label> 
    <select [(ngModel)]="selectedValue" name="pow" (change)="pow = $event.target.value; onKeyUp()" class="form-control" id="Master-Products"> 
     <option *ngFor="let pow of powers" [value]="pow">{{pow}}</option> 
    </select> 
    </div> 
</form> 

兒童成分:

export class MasterInputComponent { 
    powers: any[] = [ 'power1', 'power2', 'power3' ]; 
    submitted = false; 
    pow:string = 'Testing'; 
    selectedValue = null; 
    constructor() { } 

    onKeyUp(value): void{ 
    console.log('Value: ',this.pow); 
    } 

家長組件的模板:

<div role="tabpanel" class="tab-pane" id="accessories"> 
    <h1>ACCESSORIES</h1> 
    <h4>Testing: {{power}}</h4> 
    <master-input (change)="recieveMessage($event.target.value)"></master-input> 
    <accessories></accessories> 

家長組件:

export class AppComponent implements AfterViewInit{ 
    @ViewChild(MasterInputComponent) child; 
    title = 'Having FUN with Angular'; 
    posts: any[]; 
    power:string; 

    constructor(private service:ProductsService){} 
    ngAfterViewInit(){ 
    this.power = this.child.pow; 
    } 

    recieveMessage(value){ 
    console.log('Event: ',value); 
    this.power = value; 
    console.log('Favorite has changed') 
    } 

任何幫助將不勝感激,謝謝!

+0

在這種情況下,你會希望'輸出'和一個EventEmitter :) https://angular.io/guide/component-interaction#parent-listens-for-child-event – Alex

+0

[將數據從孩子傳遞給父組件Angular2](https://stackoverflow.com/questions/42107167/pass-data-from-child-to-parent-component-angular2) – Alex

+0

我試過這之前我目前的解決方案,我也有一個錯誤。我不記得這個錯誤。這兩種方式的工作,但我仍然最終在控制檯中的錯誤。你介意給我舉個例子嗎?你的方式很可能與我實施它的方式不同。 –

回答

0

做在你的代碼如下步驟:

(ngModelChange)= 「的onkeyup($事件)」 的代替(其他城市)= 「POW = $ event.target.value;的onkeyup()」

在你的孩子TS文件

import { Component, Output, EventEmitter } from '@angular/core'; 

@Output() sendMessage = new EventEmitter(); 

onKeyUp(e) { 
    this.sendMessage.next(e); 
} 

父HTML

<master-input (sendMessage)="recieveMessage($event)"></master-input> 
    <accessories></accessories> 

下面的代碼會增加你的父母TS

recieveMessage(msg) { 
    console.log('msg', msg) 
} 
0

試試這個:

constructor(private service:ProductsService, private cdr: ChangeDetectorRef){} 
ngAfterViewInit(){ 
    this.power = this.child.pow; 
    this.cdr.detectChanges(); 
} 

This link將拋出這個問題的確切原因光。

+0

我實際上在另一篇文章中讀到這個時,我輸入我的錯誤代碼到谷歌。沒有最終幫助我,也沒有理解這個解決方案。 –

+0

我提供的SO鏈接已經廣泛討論了這個問題。答案中的評論指出了你面臨的同樣的問題! –

+0

正如我前面提到的,我已經閱讀過那篇文章,並不喜歡這個解決方案,因爲我沒有完全理解它背後的原因。我也是新來的角,並希望瞭解我的代碼,而不是粘貼一些答案,因爲它可能會使我的代碼工作。我已經在@ AJT_82上面的評論中找到了我的問題的答案。當我有額外的時間時,我會進一步深入解決你的解決方案和背後的問題。 –