简体   繁体   English

Angular2在组件之间传递变量

[英]Angular2 passing variables between components

I have the following component below: 我有以下组件:

@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);
  }

}

I am just trying to figure out how to display the value of the this.startTest variable from the ChildComponent to the ParentComponent. 我只是想弄清楚如何显示从ChildComponent到ParentComponent的this.startTest变量的值。 Right now, the {{testEmitter}} doesn't show anything in my ParentComponent html. 目前, {{testEmitter}}在我的ParentComponent html中没有显示任何内容。 I feel like I'm close. 我觉得我接近了。 Your help is appreciated! 感谢您的帮助!

This code doesn't seem to make much sense. 这段代码似乎没有多大意义。

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

The template uses the selector <myselector> of the component it is the template of. 模板使用其模板的组件的选择器<myselector> While there are scenarios where this make sense (recursive structures like trees) this doesn't seem to be the intention here. 尽管在某些情况下这是有意义的(例如树之类的递归结构),但这似乎并不是这里的意图。

Also directives and pipes on @Component() are gone since a while and should be added to @NgModule() instead. @Component()上的directivespipes也已经消失了一段时间,应该改为添加到@NgModule() Obviously you are using some beta or RC version instead of final of Angular2 where this is still supported. 显然,您使用的是beta或RC版本,而不是仍支持Angular2的final版本。 I'd suggest to update to the newest Angular2 version. 我建议更新到最新的Angular2版本。

This might be what you want instead: 这可能是您想要的:

@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