Search code examples
angulartypescriptcomponentseventemitter

Passing input and output through a parent component


I am trying to pass some information from component A through parent component to component B.

I have a component A where I have outputs.

componentA.ts

@Output() status = new EventEmitter();
public getColor() {
   ...
   this.emit(color);
}

componentB.ts

@Input('status') status;

ngOnInit() {
  console.log(this.status) // Got EventEmitter false object
}

parent.html (Need to include component B in this HTML)

<componentA (status)="getStatus(s)"></componentA>
<componentB [status]="status"></componentB>

parent.ts

@Output() status=new EventEmitter();
public getStatus(s) {
    this.status.emit(s)
}

Currently I am getting "EventEmitter {_isScalar: false, observers: Array(0), closed: false, isStopped: false, hasError: false…" message, which I couldn't view the information passed from component A. I verify that s exists inside the getStatus function. If there's a better approach, please advice.


Solution

  • Your mistakes,

    • this.emit in component A, which should be this.status.emit(..)
    • In your component B you should be using ngOnChanges to listen the changes not ngOnInit

    Follow the below code,

    @Component({
      selector: 'my-app',
      template: `
        <div> 
          {{status}}
          <componentA (status)="getStatus($event)"></componentA>
        <componentB [status]="status"></componentB>
        </div>
      `,
    })
    export class App {
      name:string;
      status:string;
      getStatus(event){
        console.log(event)
        this.status = event
      }
      constructor() {
    
      }
    }
    @Component({
      selector: 'componentA',
      template: `
        <div>
         <button (click)="getColor()"> Click for red color</button>
    
    
        </div>
      `,
    })
    export class CompA {
      @Output() status = new EventEmitter<string>();
      public getColor() {
         this.status.emit('red');
    }
    }
    @Component({
      selector: 'componentB',
      template: `
        <div>
    
        </div>
      `,
    })
    export class CompB {
      @Input('status') status;
      ngOnChanges() {
      console.log('CompB input arrived', this.status) // Got EventEmitter false object
    }
    }
    

    LIVE DEMO