0

I try to dynamic create variables in class to store values and use it in ngModel and other placese. I know, that I can assign value to variables in ngOnInit() like this

export class Component implements OnInit{
   name: string;
   ngOnInit(){
       this.name = 'John Doe';
   }
}

But I have some problem - I get my fields from server API and don't know what and how many items I get. I can only parsing server response and assign value to new variables after get it.

I can't do it like this (TS2540: Cannot assign to 'name' because it is a constant or a read-only property.)

export class Component implements OnInit{
   ngOnInit(){
       name = 'John Doe';
   }
}

How can I assign new fields to my class in ngOnInit() or maybe in other place? (I think I can do it in constructor, but documentation say i shouldn't use it with Observable call to API and other difficult things)

Denis Savenko
  • 829
  • 1
  • 13
  • 29

2 Answers2

1

You can use something like this to accomplish that:

ngOnInit() {
  this['prop'] = 'value';
}

Here is a link to a working example: https://stackblitz.com/edit/dynamic-class-props

vince
  • 7,808
  • 3
  • 34
  • 41
1

You can add an indexer to the class to be able to use any property name and not get a compiler error:

export class Component {
    [name: string]: any;
    ngOnInit(){
        this["name"] = 'John Doe';
        this.nameaa = "dd"
    }
}

You should take care though, this means you can misspell property names and the compiler will not issue any error.

Titian Cernicova-Dragomir
  • 230,986
  • 31
  • 415
  • 357