[英]How can I pass a generic type parameter to an Angular2 component?
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, ie 我如何将该参数类型设为通用,即
@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>
It seems you can use generic type parameters in Angular 2 child components. 看来你可以在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;
}
This works without recourse either to the ViewChild
technique suggested above or to a base class technique suggested here . 无需使用上面建议的ViewChild
技术或这里建议的基类技术。
It seems that when using AOT compilation the only way to do this is to replace the generic type with 'any'. 似乎在使用AOT编译时 ,唯一的方法是用'any'替换泛型类型。 See https://github.com/angular/angular/issues/11057 请参阅https://github.com/angular/angular/issues/11057
I'm just playing with angular and I made this working by using ViewChild, by having Inner and Outer Component. 我只是玩角度,我使用ViewChild通过内部和外部组件使其工作。
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! 问候!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.