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

前端 未结 3 980

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

@Component({
    selector: \'fixed\',
    template: \'
{{value}}
\' }) e
相关标签:
3条回答
  • 2020-12-16 12:33

    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

    0 讨论(0)
  • 2020-12-16 12:38

    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!

    0 讨论(0)
  • 2020-12-16 12:39

    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.

    0 讨论(0)
提交回复
热议问题