How can I pass a generic type parameter to an Angular2 component?

早过忘川 提交于 2019-12-04 16:29:10

问题


Let's say I got a component with a fixed input parameter type,

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

How do I go about making that parameter type generic, i.e.

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

That is, how do I pass the type in the template of the parent component?

<generic ...></generic>

回答1:


It seems that when using AOT compilation the only way to do this is to replace the generic type with 'any'. See https://github.com/angular/angular/issues/11057




回答2:


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!




回答3:


It seems you can use generic type parameters in Angular 2 child components.

@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;
}

This works without recourse either to the ViewChild technique suggested above or to a base class technique suggested here.



来源:https://stackoverflow.com/questions/37235170/how-can-i-pass-a-generic-type-parameter-to-an-angular2-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!