shazia perween
shazia perween

Reputation: 607

how to add spinner template in a Angular 2 component

I have a spinner component which is used to show a spinner when HTTP request takes a little more time.

@Component({
  selector: 'my-spinner',
  template: require('./spinner.component.html'),
  styles: [require('./spinner.component.css').toString()]
})

Now, I want to use this spinner component into another component (let say "FooterComponent") which requires to pass below parameter,

[isRunning]="isRequesting"

I can pass this as part of template, but I also have to also support template for the component "FooterComponent".

Question, how can I support both?

import { Component, OnInit } from '@angular/core';
import { DataService } from '../../services/DataService';
import { SpinnerComponent } from '../spinner/spinner.component';

@Component({
  selector: 'starterTemplateFooter',
  template: require('./footer.component.html'),
  //how to add below template along with above template?
  //template: '<my-spinner [isRunning]="isRequesting"></my-spinner>'
})

export class FooterComponent {
public isRequesting: boolean;
public values: any[];

constructor(
    private _dataService: DataService) {
    this.refresh();
}

public refresh(): void {
    this.isRequesting = true;
    this._dataService.GetAll()
        .subscribe(
        result => this.values = result,
        () => this.stopRefreshing(),
        () => this.stopRefreshing());
}

private stopRefreshing() {
    this.isRequesting = false;
}
}

Upvotes: 2

Views: 700

Answers (1)

Ajey
Ajey

Reputation: 8212

Add SpinnerComponent as a directive in FooterComponent.

import { Component, OnInit } from '@angular/core';
import { DataService } from '../../services/DataService';
import { SpinnerComponent } from '../spinner/spinner.component';

@Component({
  selector: 'starterTemplateFooter',
  template: require('./footer.component.html'),
  // directives: [SpinnerComponent] // this is deprecated!
  entryComponents: [SpinnerComponent]
})

And in the footer template (footer.component.html)

Use the SpinnerComponent this way -

<my-spinner [isRunning]="isRequesting"></my-spinner>

Also, in the SpinnerComponent class mark isRunning as @Input

Ex -

export class SpinnerComponent {
    @Input() isRunning: boolean; // If it is a boolean
}

Upvotes: 1

Related Questions