Search code examples
angularangular2-components

error in two way communication in angular 2


I am getting an error like:

[ts] Declaration or statement expected

when I am passing elements from child to parent that is while practicing 2 way communication. I am not getting what is the error

//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++;
  }
}

Solution

  • The line:

    this.change.emit(11);
    

    Should be in a method like the constructor of your component:

    export MyComponent {
    
      /* ... */
    
      constructor() {
        this.change.emit(11);
      }
    }
    

    You can also place it in a ngInit method like this (add the extends to your component):

    export MyComponent extends OnInit {
    
      /* ... */
    
      ngOnInit() {
        this.change.emit(11);
      }
    }
    

    Also there seems to be a typo in your second template. Make sure there is a space between bro-root and [no]:

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