1

Assume I have an Angular (6+) component like the following:

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

    constructor() {}

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

This is a very simplistic view of what I'm trying to achieve, but basically, if my template was {{myData}} I would see my getter function being called and output the expected string. But if the getter function name to be called is held in another variable in the component (imagine in my real world scenario that I have an array of these), is there a way to tell Angular to call the respective getter whose name is held by the variable test above?

1 Answer 1

1

It seems that {{this[test]}} is working.

Sign up to request clarification or add additional context in comments.

7 Comments

nice question and answer. seems like you knew answer all along, but its good to know this kind of thing works.
I was thinking of deleting the answer, but really, it came to me a few minutes after I posted to try it. Not trying to show off or anything, but I think it may help others.
This is really more of a comment, I would say flesh the answer out a bit or remove it and add a comment
I'll leave it to the moderators to decide. Either way, I think it's good to know that you can use this in an Angular template, where normally you wouldn't.
my question is why [test] or ['myData'] works? what relation does this[] have with getters? any source to read would be appreciated.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.