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

Angular access this or service from input property

Discussão em 'Angular' iniciado por Eem, Julho 12, 2025.

  1. Eem

    Eem Guest

    I have a component with an input property.

    export class ComboboxComponent<T> implements ControlValueAccessor {

    /** The options for the combobox. */
    readonly options = input<T[]>([]);

    /** The selected value. */
    readonly value = model<T | undefined>();

    /** Get the text representation of an item */
    readonly displayWith = input.required<(option: T) => string>();
    ...


    @Component({
    selector: 'app-gauges-list',
    imports: [ComboboxComponent],
    template: `<app-combobox #gauges_list_combobox [options]="gauges" placeholder="Select a gauge" [displayWith]="displayWith" (valueChange)=onValueChange($event) />`
    })
    export class GaugesListComponent implements OnInit {
    ...
    displayWith(value: string): string {
    }
    ...


    I set the property to a getter method in a parent component. But I can not use this in the getter method. I need to access either this or inject a service somehow. Because the value is a reference to a map that contains the object I need to use.

    displayWith(value: string): string {
    let gauge = this.gs.getDirect(value);
    return gauge?.type + " " + gauge?.symbol;
    }


    ERROR TypeError: can't access property "gs", this is undefined


    I try to use inject but this also not work.

    displayWith(value: string): string {
    let gs = inject(GaugesService);
    let gauge = gs.getDirect(value);
    return gauge?.type + " " + gauge?.symbol;
    }


    The `_GaugesService` token injection failed. `inject()` function must be called from an injection context such as a constructor, a factory function, a field initializer, or a function used with `runInInjectionContext`.


    How do you access this or inject a service with this? It should be possible somehow. The only solution I can think is to use a global map that I can access without this. Like a global constant. But this is contrary to the whole concept of dependency injection.

    Continue reading...

Compartilhe esta Página