Using a dynamic variable to access an Angular getter within a template expression

Imagine having an Angular (6+) component structured like this example:

@Component({
        selector: 'my-component',
        template: '{{test}}'
    })
    export class MyComponent {
        test = 'myData';

        constructor() {}

        get myData(): string {
            return 'this is what I want to display in the template';
        }
    }
    

This code snippet showcases a basic concept that highlights the goal at hand. In essence, when the template references {{myData}}, it triggers the corresponding getter function and displays the anticipated string output. However, if the name of the getter function being called is stored in another variable within the component (such as an array containing multiple options), is there a method for instructing Angular to invoke the appropriate getter based on the value assigned to the variable test?

Answer №1

Apparently, the function {{this[test]}} is functional.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The specified type 'x' cannot be assigned to the type 'x'. Error code: 2322

I encountered an issue with the code in @/components/ui/billboard.tsx file import { Billboard } from "@/types" interface BillboardProps { data: Billboard; }; const BillboardComponent: React.FC<BillboardProps> = ({ data }) => ...

We've encountered an issue with Redux and Typescript: 'Unable to find property 'prop' in type 'string[]'

When attempting to fetch data in redux and return only a portion of it, I encountered an issue with Typescript stating that "Property 'xxx' does not exist on type 'string[]'". I have reviewed the interface and initialState, but I am una ...

Typescript: Subscribed information mysteriously disappeared

[ Voting to avoid putting everything inside ngOnit because I need to reuse the API response and model array in multiple functions. Need a way to reuse without cluttering up ngOnInit. I could simply call subscribe repeatedly in each function to solve the p ...

Ways to secure mat tab for verification

When clicking on a mat tab, I want it to display a warning asking if the user is sure. If the user selects yes, then the tab should change; otherwise, the user should remain on the same tab. However, currently, when I click on a tab, it changes before sh ...

Choose particular text within the editorState

I'm in the process of developing a sophisticated text editor utilizing draftjs. Take a look at this basic codesandbox to get a better understanding of the issue at hand. One of the challenges I'm facing is with a helper function called getCurren ...

Set the initial index position to 0 for the property type

Looking to define a type for the following scenario: categories.categories[0].category.map((c: CategoryObject) => ({ category: c.name[0]._text[0], Can we specify index 0 in the type declaration? For example: type CategoryObject = { name[0]: { _te ...

manipulator route in Nest.js

I have the following PATCH request: http://localhost:3000/tasks/566-344334-3321/status. The handler for this request is written as: @Patch('/:id/status') updateTaskStatus() { // implementation here return "got through"; } I am struggling t ...

What is the best way to extract data from API console output using Angular?

Currently, I am deeply involved in a full stack project utilizing asp.net and angularjs. My goal is to extract output response from the Swagger API. You can view the code I've written for this purpose here: (https://i.stack.imgur.com/vLyIE.png) The A ...

What does 'this' refer to in a JavaScript function that is inside an object?

I'm currently working with a JavaScript code snippet that looks like the example below. On this particular line, this.orgBusinessKey = this.user.noaOrganisationList[0].businessKey; I'm wondering if the this scope will contain the user instance ...

Extracting data from a JSON object using Angular 2

I need advice on the most efficient way to handle JSON within my angular2 application. The JSON data I am working with includes: { "rightUpperLogoId": { "id": 100000, "value": "" }, "navbarBackgroundColorIdCss": { "id" ...

Inquiring about using React typescript useRef function for improved performance

Creating a reusable hook to manipulate the DOM is the objective. Sample Code: import { useEffect, useRef } from 'react'; function useFocus() { const domRef = useRef<HTMLElement | null>(null); useEffect(() => { domRef.current?.f ...

Encountering difficulties in sending a POST request using HTTP in Angular 4

While working on a small Angular frontend with REST api support in the backend, I encountered a peculiar issue. When attempting to execute http.post(url, data, params), nothing seems to happen. There are no signs of the request reaching the webserver, and ...

Creating a TypeScript type or interface that represents an object with one of many keys or simply a string

I am tasked with creating an interface that can either be a string or an object with one of three specific keys. The function I have takes care of different errors and returns the appropriate message: export const determineError = (error: ServerAlerts): ...

What steps should I take to ensure that this test covers all possible scenarios?

I recently started learning React development and am currently exploring testing with Jest and React Testing Library (RTL). However, I'm facing challenges in achieving complete test coverage for the component code below: import { CustomCardActions, ...

Transform leaflet marker plugin into Typescript format

I recently discovered a leaflet extension that conceals map markers if they fall outside the boundaries of the current view map. import L from 'leaflet'; L.Marker.MyMarker= L.Marker.extend({}).addInitHook(function (this: ILazyMarker) { this ...

NgrxStore - An initial item has been added twice to the array

Currently experimenting with ngrx store and manipulating elements within an array, such as deleting, fetching, and editing, works smoothly. However, a challenge arises when inserting an object into the array for the first time, duplicating the entry unless ...

What is the best method for incorporating a variable into an Ionic iframe?

Can anyone help with integrating a variable into an Ionic iframe? <ion-content> <iframe src="http://local/server_api/pr.php?p={{insert-variable-here}}" style="width: 100%; min-height: 100%; height: 100%;" frameborder= ...

Typescript includes empty spaces in its duplicate-checking process

I have been working on removing duplicate values from an array using the following code: for (var i = 0; i < a.length; i++) obj[a[i]] = a[i] a = new Array(); // Checking each object with keys to remove duplicates. for (var key ...

Encountered a type error while iterating through the FirebaseListObservable containing an array of any data

I am currently retrieving a collection from Firebase and attempting to iterate over the collection, returning instances of objects. Here is what my code looks like: class Todo { constructor(public text: string) { } } this.db.list('todos').map ...

The scrollbar in the InfoWindow of an Angular GoogleMaps marker is not being hidden

Is it possible to customize the popup info window that appears when a marker is clicked, without having a scrollbar on the right if the content overflows? Visit this link for an image (image didn't load when using the image template) I've attem ...