2016-12-13 62 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