1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

Generic component with default value for generic type

Discussão em 'Angular' iniciado por Petr Averyanov, Outubro 13, 2024.

  1. Lets say u have component with two inputs: object: T and propName: keyof T.

    @Component(...)
    class MyC<T> {
    @Input() object: T;
    @Input() propName: keyof T;
    }

    <my-c [object]="{prop: 1}" [propName]="'prop'"></my-c> <!-- ok -->
    <my-c [object]="{prop: 1}" [propName]="'prop222'"></my-c> <!-- error -->


    My goal is to provide default value for propName e.g. myProp, so desired result:

    <my-c [object]="{propName: 1}"></my-c> <!-- ok -->
    <my-c [object]="{otherPropName: 1}"></my-c> <!-- error -->
    <my-c [object]="{otherPropName: 1}" [propName]="'otherPropName'"></my-c> <!-- ok-->


    What I tried so far:

    • direct approach propName: keyof T = 'myProp' (results in compilation error in class itself)
    • changing MyC generic type (something like propName: T, object: {[key in T]: any}) (results in compilation error in class itself)

    I hope there is a solution, or at least workaround.

    Continue reading...

Compartilhe esta Página