5

My main HTML

<div>
  <block></block>
  <block></block>
</div>

My Component

import {Component} from '@angular/core';
import {Observable} from 'rxjs/rx';
import {HTTP_PROVIDERS} from '@angular/http';
import {OnInit} from '@angular/core';
import {TestService} from './data.service'

@Component({
    selector : 'block',
    template : `
      <div class="col-lg-4" style="color:blue">{{_list && _list[0].name}}</div> 
`,
providers : [HTTP_PROVIDERS,TestService]
})
export class TestComponent implements OnInit{
    _list : any[];
    constructor(private _testDataService : TestService){}
    ngOnInit(){
        this._testDataService.getData()
            .subscribe(list => this._list = list);
    }

}

I want to reuse the component in the same page to show different data for different service calls

praveen
  • 489
  • 6
  • 12

1 Answers1

0

We can achieve this by passing data from view to the Component as an attribute.

<div>
  <block test="block1"></block>
  <block test="block2"></block>
</div>

Then in the component get the value of test by using the @Input decorator

import {Component} from '@angular/core';
import {Observable} from 'rxjs/rx';
import {HTTP_PROVIDERS} from '@angular/http';
import {OnInit} from '@angular/core';
import {TestService} from './data.service'

@Component({
  selector : 'block',
  template : `
    <div class="col-lg-4" style="color:blue">{{_list && _list[0].name}} 
    </div> 
    `,
  providers : [HTTP_PROVIDERS, TestService]
})
export class TestComponent implements OnInit{

  @Input() test;

  _list : any[];

  constructor(private _testDataService : TestService){}

  ngOnInit(){
    this._testDataService.getData(this.test)
      .subscribe(list => this._list = list);
  }
}

After receiving the value from view, pass the same to the service depending on which you get the data.

Wherever angular sees a selector in the view, it will create a new instance of that.

georg-un
  • 1,123
  • 13
  • 24
praveen
  • 489
  • 6
  • 12
  • I am facing a problem with this approach. For me, the value of test as "Block1" is the only value passed irrespective of the block used – Tarun Bhatt Jul 15 '18 at 08:22
  • 1
    Using services to retrieve data in a re-usable Component is a big anti-pattern. Re-usable components should only have inputs and outputs. – George Oiko Apr 24 '19 at 13:37