Angular2 .. Using the same component to display different data on the same page depending on the response of the service / Reusing the component

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 a component on the same page to display different data for different service calls

+2
source share
1 answer

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

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

Then, in the component, get the test value using @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 the view, pass the same to the service, depending on what data you receive.

When angular sees the selector in the view, it will create a new instance of this file.

+1
source

Source: https://habr.com/ru/post/1244599/


All Articles