如何在Angular 2组件中添加微调器模板

时间:2016-12-20 04:16:27

标签: angular

我有一个微调器组件,用于在HTTP请求花费更多时间时显示微调器。

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

现在,我想将这个微调器组件用于另一个组件(比如说" FooterComponent"),它需要传递下面的参数,

[isRunning]="isRequesting"

我可以将此作为模板的一部分传递,但我还必须支持组件的模板" 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'),
  //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;
}
}

1 个答案:

答案 0 :(得分:1)

在FooterComponent中添加SpinnerComponent作为指令。

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]
})

在页脚模板(footer.component.html)

以这种方式使用SpinnerComponent -

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

此外,在SpinnerComponent类中将isRunning标记为@Input

前 -

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