2016-12-13 116 views
0

我有組件A,裏面有組件B. 組件A有一個顯示綁定屬性的模板。綁定問題與嵌套組件

我點擊組件B按鈕,它發出組件A的消息。 組件A捕獲並更新屬性,但模板不刷新該值。

如果我點擊另一次在這裏,我顯示的信息。

因此,由於某種原因,它不第一次使用消息刷新模板,但是爲什麼?

我檢查了日誌,並正確地擊中了onNotify。

A組分

@Component({ 
    selector: '...', 
    templateUrl: '...' 
}) 
export class ComponentA { 

    message: string; 

    constructor(...) {...} 

    onNotify(message: string): void { 
     this.message = message; 
    } 
} 

A組份模板

<div class="message"> 
    {{message}} 
</div> 
<component-b (notify)='onNotify($event)'></component-b> 

B組分

@Component({ 
    selector: 'component-b', 
    templateUrl: '...' 
}) 
export class ComponentB { 

    @Output() notify: EventEmitter<string> = new EventEmitter<string>(); 

    constructor(...) {...} 

    onClick() { 
     this.notify.emit('Message'); 
    } 
} 

這裏是一些我用

"@angular/common": "2.3.0", 
"@angular/compiler": "2.3.0", 
"@angular/core": "2.3.0", 
"@angular/forms": "2.3.0", 
"@angular/http": "2.3.0", 
"@angular/platform-browser": "2.3.0", 
"@angular/platform-browser-dynamic": "2.3.0", 
"@angular/platform-server": "2.3.0", 
"@angular/router": "3.3.0", 
的DEPS的

感謝您的幫助,以瞭解這一點。

+0

它看起來像您從您的帖子刪除了一些冗餘代碼,但它會更容易幫助,如果我們能看到的所有代碼。例如,您是否在完整的代碼中爲組件指定了changeDetection?如果是這樣,你在那裏有什麼價值? – mcgraphix

+0

這基本上是我使用的代碼。我沒有任何具體的變化檢測。 – user4809674

回答

0

我找到了解決方法。我不滿意它,所以如果有人找到一個乾淨的修復程序...

我強制框架來檢測我的onNotify方法的變化。

我從@angular/core進口ChangeDetectorRef。 並在我的屬性更新後使用detectChanges()方法。

0

ChangeDetectorRef是你應該使用什麼這樣的:

@Component({ 
    selector: '...', 
    templateUrl: '...' 
}) 
export class ComponentA { 
     message: string; 

     constructor(private ref: ChangeDetectorRef) { } 

     onNotify(message: string): void { 
     this.message = message; 
     // trigger the view update 
     this.ref.markForCheck(); 
     } 
} 
+0

它不工作,我仍然需要點擊兩次才能顯示消息。 用detectChanges()代替markForCheck()它的工作。 – user4809674