0

I need a way to bind a variable in a string.

for example in Ts:

name = '{{first}}';

and in HTML if I have :

 <input [(ngModel)]="first">
 <div> {{name}} <div>

This should return what ever is being typed in the input and not '{{first}}' how can I achieve that ?

I Have a test code at stackblitz

Sven.hig
  • 4,449
  • 2
  • 8
  • 18
Nar
  • 1

2 Answers2

0

You cannot use interpolation {{ }} in the controller. It is restricted to HTML templates.

What you could do is assign the member variable using this keyword.

export class AppComponent  {
  name = 'Angular';
  name1 = this.name;
}

However this is a one-time assignment. Any changes to name variable using the <input> tag won't affect the name1 variable.

ruth
  • 29,535
  • 4
  • 30
  • 57
  • Actually we are getting the interpolation string straight from Database and can not assign it in controller. I can understand that I m assigning the value as a string so its being resolved as a string, but I want a way it can be parsed as an expression. – Nar Jun 17 '20 at 20:34
  • 1
    @Nar: So for eg. if the database sends `{{ id }}`, do we assume there already is an existing member variable like `public id = 5`? If not, you cannot use the interpolation anyway. To use the interpolation, the value must exist in the controller. – ruth Jun 17 '20 at 21:18
  • Yes, we are using formly and both the fields and the model will be passed to UI from an API. So the {{ id }} will be in the model and variable id will be two way binded with one of the field in the UI. The model data will be in the controller. – Nar Jun 18 '20 at 12:06
  • If the backend sends both `id` and `{{ id }}`, then what exactly is the purpose of `{{ id }}`? You could ignore it and bind to the `id` variable directly. – ruth Jun 18 '20 at 13:07
  • 1
    The string that comes as interpolation from DB is more like {{ID}} + {{ID1}} more like an expression based on input from the user for one or more fields. https://stackoverflow.com/questions/44077994/angular2-evaluate-template-from-string-inside-a-component this post had the answer I needed. Thanks for answering! – Nar Jun 18 '20 at 13:41
0

I might have misunderstood your requirements but Angular already supports two way binding

Updated stackblitz here.

Manish
  • 6,106
  • 19
  • 64
  • 90