簡體   English   中英

如何將泛型類型參數傳遞給Angular2組件?

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

假設我有一個具有固定輸入參數類型的組件,

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

看來你可以在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;
}

無需使用上面建議的ViewChild技術或這里建議的基類技術。

似乎在使用AOT編譯時 ,唯一的方法是用'any'替換泛型類型。 請參閱https://github.com/angular/angular/issues/11057

我只是玩角度,我使用ViewChild通過內部和外部組件使其工作。

在組件的內部組件聲明中就像:

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

在路由器調用的外部組件中我做了:

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

我不知道這是一個好方法,但它有效。

問候!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM