繁体   English   中英

Angular2在组件之间传递变量

[英]Angular2 passing variables between components

我有以下组件:

@Component({
  selector: 'myselector',
  providers: [ ],
  directives: [ ChildComponent],
  pipes: [ ],
  template: '<myselector>This is {{testEmitter}}</myselector>'
})

export class ParentComponent{
  @Input() testEmitter;
  constructor(){
  }
}

//My Child class goes as such:
@Component({
  selector: 'childselector',
  templateUrl: '<childselector><input type="text" (focus)="beginTest()"/></childselector>',
  pipes: [],
  directives: []
})
export class ChildComponent{
  @Output() testEmitter: EventEmitter = new EventEmitter();
  startTest: boolean = false;

  constructor() {

  }
  beginTest(){
      this.startTest = !this.startTest;
      this.testEmitter.emit(this.startTest);
  }

}

我只是想弄清楚如何显示从ChildComponent到ParentComponent的this.startTest变量的值。 目前, {{testEmitter}}在我的ParentComponent html中没有显示任何内容。 我觉得我接近了。 感谢您的帮助!

这段代码似乎没有多大意义。

@Component({
  selector: 'myselector',
  providers: [ ],
  directives: [ ChildComponent],
  pipes: [ ],
  template: '<myselector>This is {{testEmitter}}</myselector>'
})

模板使用其模板的组件的选择器<myselector> 尽管在某些情况下这是有意义的(例如树之类的递归结构),但这似乎并不是这里的意图。

@Component()上的directivespipes也已经消失了一段时间,应该改为添加到@NgModule() 显然,您使用的是beta或RC版本,而不是仍支持Angular2的final版本。 我建议更新到最新的Angular2版本。

这可能是您想要的:

@Component({
  selector: 'parentselector',
  directives: [ChildComponent],
  template: '<childselector (testEmitter)="testEmitter=$event">This is {{testEmitter}}</childselector>'
})

export class ParentComponent{
  @Input() testEmitter;
}
@Component({
  selector: 'childselector',
  templateUrl: '<input type="text" (focus)="beginTest()"/>',
})
export class ChildComponent{
  @Output() testEmitter: EventEmitter = new EventEmitter();
  startTest: boolean = false;

  beginTest(){
      this.startTest = !this.startTest;
      this.testEmitter.emit(this.startTest);
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM