2017-04-09 100 views
0

我搜索一下与Angular2组件我尝试在此模式下,但没有按之间的通信科技工作Angular2组件间的通信

模板variantpages.component.html内容本

<button (click)="changetext()">Change</button> 
<child></child> 



@Component({ 
    selector: 'menu-left', 
    templateUrl: './app/pages/variantpages.component.html' 
}) 

export class AppComponent{ 


child = new ChildComponent(); 


changetext(){ this.child.changetext2()} 

} 
@Component({ 
    selector: 'child', 
    template: `<p>page of {{ pageCount }}</p>` 
}) 

export class ChildComponent{ 

@Input() photo:string = "ciao ciao"; 

@Output() valueChange = new EventEmitter(); 


pageCount:number; 
constructor(){ this.pageCount = 0; } 

changetext2(){ 
     this.pageCount++; 
     this.valueChange.emit(this.pageCount); 
     console.log(this.pageCount); 
    } 
} 

所以控制台日志显示增量编号,但pageCount停留0

谢谢

+0

那么你的HTML中包含更新后 – Aravind

+1

不看太密切(这意味着有可能是其他的问题),但发现以下...检查*“家长监听子女事件” *和正确使用输出到这个链接:https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#parent-to-view-child请注意该例子中的childtag。提示:''是不够的;),并使用'ViewChild'的@代替'孩子=新ChildComponent();'链接我提供的地址这两个问题;) – Alex

+0

喜感谢回答我把HTML的一部分,问题是组件调用方法changetext2,我看到在控制台中的增量,但不改变在页面 – corsaro

回答

0

好吧,我解决了EventEmitter但这项工作只能由父母和孩子,现在我的问题是在A组份期不同,如果我有两个不同的组成部分,我想用一个按钮(点击)来改变串在B组份,我把这种方法的setName

组分A

constructor(private appComponent: AppComponent){ } 
setName(newName: string) { 
     this.appComponent.name = newName; 
     console.log(this.name); 
     } 

组分B

@Input() name: string = "Angular3" 

控制台显示新的字符串,但该名称不会改变

+0

您可以使用共享服务类来进行这种类型的通信。有关更多信息,请参阅:https://angular.io/docs/ts/latest/cookbook/component-communication.html – Brandon