How do I share data between components in Angular 2?

后端 未结 6 613
故里飘歌
故里飘歌 2020-11-22 05:04

In Angular 1.x.x you simply ask for the same service and you end up with the same instance, making it possible to share the data in the service.

Now in Angular 2 I h

6条回答
  •  甜味超标
    2020-11-22 05:41

    You must use inputs and outputs of a @Component decorator. Here is the most basic example of using both;

    import { bootstrap } from 'angular2/platform/browser';
    import { Component, EventEmitter } from 'angular2/core';
    import { NgFor } from 'angular2/common';
    
    @Component({
      selector: 'sub-component',
      inputs: ['items'],
      outputs: ['onItemSelected'],
      directives: [NgFor],
      template: `
        
    {{ item }}
    ` }) class SubComponent { onItemSelected: EventEmitter; items: string[]; constructor() { this.onItemSelected = new EventEmitter(); } select(i) { this.onItemSelected.emit(this.items[i]); } } @Component({ selector: 'app', directives: [SubComponent], template: `
    ` }) class App { items: string[]; constructor() { this.items = ['item1', 'item2', 'item3']; } itemSelected(item: string): void { console.log('Selected item:', item); } } bootstrap(App);

提交回复
热议问题