Amritraj
Amritraj

Reputation: 25

How do I get inputs and raise events for the outside world in Angular?

I would like to know how can one get inputs from the outside world and raise custom events that bubbles up to the outside world (i.e. outside of angular components). I understand I cannot get @Input() in the root component. Then how can I do the following:

  1. Pass an array of object (say T[]) to my Angular components <app-root> from outside of angular.
  2. raise an event from <app-grandchild> such that the event bubbles out of angular components and hits the DOM tree root or <body>.

Assume the following DOM hierarchy:

<body>
  <app-root>
    <app-child>
      <app-grandchild></app-grandchild>
    </app-child>
  </app-root>
</body>

Upvotes: 1

Views: 1359

Answers (1)

Ricardo Fornes
Ricardo Fornes

Reputation: 382

Your question requires an explanation of a couple of concepts from Angular: Component Interaction and content projection.

I've put together an example that combines both to meet what you described in your question:

@Component({
  selector: 'app-child',
  template: `
  <ul>
      <li *ngFor="let obj of arrayOfObjects"> {{ obj.id }} </li>
  </ul>
  <ng-content></ng-content>
  `,
})
class AppChildComponent {
    @Input() arrayOfObjects: object[];
}

@Component({
  selector: 'app-grandchild',
  template: `Am the grandchild!`,
})
class AppGrandChildComponent implements OnInit {
    @Output() somethingHappened = new EventEmitter<string>();

  ngOnInit(){
    this.somethingHappened.emit('yellow');
  }
}


@Component({
  selector: 'app-root',
  template: `
    <app-child [arrayOfObjects]="[
      {id: '123'},
      {id: '456'}
    ]">
        <app-grandchild 
          (somethingHappened)="handleSomething($event)">
        </app-grandchild>
    </app-child>
  `,
})
class AppComponent {
    handleSomething(event){
    document.body.style.backgroundColor = event;
  }
}

Full example here: https://jsfiddle.net/c945j08v/1/

I strongly recommend you reading more on Angular Docs & Blog.

I hope this helps.

Upvotes: 1

Related Questions