2016-04-09 56 views
1

嗨我有一種情況,我想更改組件內部屬性的值。以下是我迄今爲止:更改子組件中屬性的值不起作用

import {Component, OnInit} from 'angular2/core'; 
import {TinymceComponent} from './../../../common/components/tinymce.component'; 

@Component({ 
    selector: 'templates', 
    directives: [TinymceComponent], 
    template: `<button (click)="update()">Update</button> 
       <tinymce [(description)]="product.description"></tinymce>` 
}) 
export class ProductEditComponent implements OnInit { 
    public product: any; 

    public ngOnInit() { 
     this.product = { 
      description: 'hello world' 
     } 
    } 

    public update(){ 
     console.log(this.product) 
    } 
} 

這是我TinyMceComponent:

import {Component, OnInit, Input} from 'angular2/core'; 
declare var tinymce: any; 

@Component({ 
    selector: 'tinymce', 
    template: '<textarea id="tinymce-editor"></textarea>', 
}) 
export class TinymceComponent implements OnInit { 
    @Input() description: string; 

    public ngOnInit() {  
     setTimeout(() => this.description = 'new text', 5000) 
    } 
} 

什麼此刻正在發生的事情是product.description的值保持爲「世界你好」後,即使setTimeout函數得到執行並將描述設置爲'new text'

我想要做的是能夠從TinyMceComponent中的產品模型中更改description屬性。現在我不確定我的方法是否正確我認爲它會起作用,因爲像這樣的東西曾經在角1中工作,但我可能是錯的。

誰能告訴我怎麼做到這一點?

+0

您沒有使用TinymceComponent的模板中的描述。 –

回答

2

我無法複製Plunker example顯示hello world並且在5秒後更改爲new text

單程結合(父母對子女)唯一[description]足夠

[(description)]="product.description" 

是雙向綁定,並且將需要在

@Output() descriptionChange:EventEmitter = new EventEmitter(); 

TinymceComponent

+0

這是真的,但如果你更新並打開控制檯,你會看到產品對象仍然打印'你好世界'而不是'新文本',這是我的問題產品型號不會更新....我可能是在這裏丟失了一些東西,或者我的方法不適合我想要實現的目標 – aleczandru

+0

@miconyks示例顯示了您需要的東西。 –

3

您應該只使用方括號,因爲您只定義了input屬性。你的組件似乎沒有發出任何事件。所以,你的模板應該是這樣的:

<button (click)="update()">Update</button> 
<tinymce [description]="product.description"></tinymce> 

方括號[]@Input屬性和括號()@Output性能。

2

working Demo

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

@Output() descriptionChange:EventEmitter= new EventEmitter() 

ngOnInit() {  
     //setTimeout(() => this.description = 'new text', 5000) 
     this.descriptionChange.emit("new Text"); 
}