【问题标题】:Angular2 Communication Between ComponentsAngular2组件之间的通信
【发布时间】:2017-09-04 17:33:38
【问题描述】:

我用 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

谢谢

【问题讨论】:

  • 你的 html 包含什么更新它来发布
  • 没有仔细观察(意味着可能还有其他问题),但注意到以下...检查“parent listeners for child event”并正确使用此链接中的输出:angular.io/docs/ts/latest/cookbook/… 请注意该示例中的子标签。提示:&lt;child&gt;&lt;/child&gt; 是不够的 ;) 并使用 @ViewChild 而不是 child = new ChildComponent(); 我提供的链接解决了这两个问题 ;)
  • 嗨,谢谢你的回答我把html的一部分,问题是组件调用方法changetext2,我在控制台中看到增量,但在页面中没有改变
  • 首先你应该使用 ViewChild(查看我给你的链接)。如果问题仍然存在,请提供 plunker。

标签: angular components angular2-injection angular2-inputs


【解决方案1】:

好的,我用 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"

控制台显示新字符串,但名称不变

【讨论】:

猜你喜欢
  • 2016-05-01
  • 2016-12-29
  • 2017-05-04
  • 2017-10-30
  • 1970-01-01
  • 2018-03-23
  • 2018-12-13
  • 2018-02-17
  • 2023-04-02
相关资源
最近更新 更多