2016-06-21 32 views
0

(節省一些閱讀 - 歸結爲缺少「這個」引用@ Input'ed變量時的問題)互動與傳遞給Angular2組件作爲輸入對象

我有一個父類 - 這將(最終)顯示「QuestionComponents」列表。

父類模板的相關部分如下:

<question [(justText)]="testText" [(justObj)]="testObj" [(myQuestion)]="singleQuestion"></question> 

我只想說我越來越從HTTP服務調用的「singleQuestion」對象。 Question類(其中「singleQuestion」是一個實例)具有基本的「toString」方法,可以更輕鬆地進行輸出調試。

testText,textObj和singleQuestion都是我測試時日益複雜的對象。就目前而言,這是非常基本的,並且在我理解時只有一個「問題」。

孩子「QuestionComponent」看起來是這樣的:

@Component ({ 
    selector: 
     'question', 
    templateUrl: 
     './app/components/question/question.component.html', 
    directives: [FORM_DIRECTIVES], 

}) 


export class QuestionComponent { 

    @Input() myQuestion:USGSQuestion 
    @Input() justText:string 
    @Input() justObj:object 

    constructor() { 

    } 

    onClick() { 
     myQuestion.generalInfo.label = "changed"; 
     console.log("change attempted"); 
    } 
} 

注意:隨着時間推移,我需要能夠做到與被傳遞到QuestionComponent對象有些沉重的交互。實際上,我的首選是將Question對象傳遞給構造函數,但將數據傳遞到組件構造函數似乎不起作用。 (我離題了)爲了試圖檢查我如何與傳遞的數據進行交互,我構建了onClick按鈕並試圖改變@ Input'ed變量之一。

的子對象的模板是這樣:

<div *ngIf="!justText"> 
    no text passed 
</div> 
<div *ngIf="justText"> 
    <b>Here is the passed Text:</b><br> 
    {{justText}} <br> 
</div> 
<br> 
<div *ngIf="!justObj"> 
    no obj passed 
</div> 
<div *ngIf="justObj"> 
    <b>Here is the passed JSON:</b><br> 
    Foo: {{justObj.foo}} <br> 
    Baz: {{justObj.baz}} 
</div> 
<br> 
<div class="question"> 
    <i>I am a question spot</i> 

    <div *ngIf="!myQuestion"> 
     Loading Question... 
    </div> 
    <div *ngIf="myQuestion"> 
     <b>Here is the passed question:</b><br> 
     {{myQuestion}} <br> 
    </div> 
</div> 

<button (click)="onClick()">Clickit</button> 

我怎麼到類裏面的@ Input'ed對象的引用? (在這種情況下,我將如何修改「myQuestion」中的「onClick()」函數?......以及,其次,我將如何確保得到傳遞給視圖的更新更改的對象?


我應該注意到我已經嘗試通過調用的onClick從「查看」傳值回,像這樣: (Change按鈕來:)

<button (click)="onClick(myQuestion)">Clickit</button> 

(和更改的onClick到:)

onClick(q) { q.generalInfo.label = "changed"; } 

這沒有奏效。

回答

1

我是個白癡。

經過幾個小時的研究和搜索(問之前),這一切都歸結爲添加「這個」。

...在"myQuestion.generalInfo.label = "changed";"應該已經"this.myQuestion.generalInfo.label = "changed";"

有些日子,你必須熱愛編程,不是嗎?

相關問題