angular 2 中的双向通信错误

error in two way communication in angular 2

我收到如下错误:

[ts] Declaration or statement expected

当我将元素从 child 传递到 parent 时,即在练习双向通信时。我不知道错误是什么

//child 

import { Component, Input, EventEmitter, Output } from '@angular/core';
//import { Hero } from './app.hero';

@Component({
  selector: 'bro-root',
  template:` 
    <div>
      <h1>name:</h1>
      <h2>{{fname}}</h2>
      <h2>{{sname}}</h2>
      <h2 style="background-color:red;width:80px;">{{bruz}}</h2>
      <h2 style="background-color:red;width:80px;">{{no}}</h2>
    </div>
  `,
  })
export class ChildComponent {
  fname:string = "tom";
  sname:string = "jerry";
  gender:string = "male";
  age:number = 20;

  @Input()
  bruz:string;
  @Input()
  no:number;
  @Output()
  change:EventEmitter<number> = new EventEmitter<number>();

  this.change.emit(11);
}


//parent

import { Component, Input } from '@angular/core';
import { ChildComponent } from './app.childcomponent';
//import { Hero } from './app.Hero';

@Component({
  selector: 'app-root',
  template: `
    <bro-root[no]="count" (change)="updateFromChild($event)"></bro-root>
  `,
})
export class AppComponent {
  title = 'app works!';
  count:number = 10;

  updateFromChild($event) {
    this.count++;
  }
}

行:

this.change.emit(11);

应该在类似于组件构造函数的方法中:

export MyComponent {

  /* ... */

  constructor() {
    this.change.emit(11);
  }
}

您也可以像这样将它放在 ngInit 方法中(将 extends 添加到您的组件):

export MyComponent extends OnInit {

  /* ... */

  ngOnInit() {
    this.change.emit(11);
  }
}

您的第二个模板中似乎也有错字。确保 bro-root[no] 之间有一个 space:

<bro-root [no]="count" (change)="updateFromChild($event)"></bro-root>