-1

I am trying to get a name of a component from a json file and via a method add 'this' to its name.

import { MyComponent } from './Mycomponent';

...

MyComponent = MyComponent;


data = [
    {
      "name": "MyComponent"
    }
  ];

The method:

  test(name: any) {
    return this.[name];
  }

usage example:

this.test('MyComponent');

Expected output is:

this.MyComponent

When I try: this.[name]

I get Identifier expected.

How can I fix this?

deszok
  • 145
  • 2
  • 14

1 Answers1

1

You are trying to something like this, for example:

TS

componentName: any;

  data = [
    {
      name: 'MyComponent',
    },
  ];

  test(name: any) {
    this.componentName = `this.${name}`; // storing this.Mycomponent name to variable for displaying 
    return `this.${name}`;
  }

  testbtnHandle() {
    this.test('MyComponent');   // it will call the test function with MyComponent name parameter
  }

HTML

{{componentName}} // for display


<button type="button" (click)="testbtnHandle()">click</button>

Here you can check or play with code.

halfer
  • 19,824
  • 17
  • 99
  • 186
Kiran Mistry
  • 2,614
  • 3
  • 12
  • 28