如何将泛型类型参数传递给Angular2组件?

时间:2016-05-15 06:16:24

标签: angular angular2-template

我们说我得到了一个具有固定输入参数类型的组件

@Component({
    selector: 'fixed',
    template: '<div>{{value}}</div>'
})
export class FixedComponent {
    @Input() value: string;
}

如何将该参数类型设为通用的,即

@Component({
    selector: 'generic',
    template: '<div>{{value}}</div>'
})
export class GenericComponent<T> {
    @Input() value: T;
}

也就是说,如何在父组件的模板中传递类型?

<generic ...></generic>

3 个答案:

答案 0 :(得分:2)

似乎您可以在Angular 2子组件中使用泛型类型参数。

@Component({
  selector: 'app-child',
  template: '<p>Generic Child</p><p>{{cp}}</p>'
})
export class GenericChildComponent<T> {
  @Input() cp: T;
}

import { GenericChildComponent } from './generic-child.component';
@Component({
  selector: 'app-root',
  template: '<app-child [cp]="p1"></app-child><hr /><app-child [cp]="p2"></app-child>',
  directives: [GenericChildComponent]
})
export class ParentComponent {
  p1: string = 'property 1';
  p2: number = 100;
}

无法使用建议aboveViewChild技术或建议here的基类技术。

答案 1 :(得分:2)

似乎在使用AOT compilation时,执行此操作的唯一方法是使用&#39; any&#39;替换泛型类型。见https://github.com/angular/angular/issues/11057

答案 2 :(得分:1)

I'm just playing with angular and I made this working by using ViewChild, by having Inner and Outer Component.

In inner component declaration of component is like:

@Injectable() 
@Component({
selector: 'inner-selector',
templateUrl: ...,
styleUrls: ...,
directives: [
...]
export class InnerComponent**<T>**  ...

in outer component which called by router I did:

import {Component} from '@angular/core';
import {InnerComponent} from '../components/inner.component';
import {ViewChild  } from '@angular/core';

@Component({
  selector:     'demo-app',
   template:  '<inner-selector></inner-selector>',
directives: [InnerComponent]
})
export class TestPage { 

  @ViewChild(InnerComponent)
  **private innerComponent:InnerComponent<MPSalesHeader>;**
};

I don't know is this a good way, but it worked.

Regards!