Search code examples
angulartypescriptstring-interpolation

How to change bound variable dynamically in Angular?


I think, everyone knows, how interpolation works, and we can easily interpolate single variable (may be this interpretation is not fully correct, but you will understand what I mean when will take a look at the code). But what if we want to switch between two different variables dynamically? For example, we have two class properties:

public first: string = '"first" variable activated';
public second: string = '"second" variable activated';

And have two radio buttons, bound to activeVariableName class property:

<input type="radio" value="first" [(ngModel)]="activeVariableName">
<input type="radio" value="second" [(ngModel)]="activeVariableName">

We can interpolate like this:

<h1>{{activeVariableName}}</h1>

But this way, we will see just first or second, which are class properties names.

So my question is: "How to display values of this properties, but not just names?"

Here is a STACKBLITZ


Solution

  • You missed off the binding brackets [], so the values are first and second. try:

    <input type="radio" [value]="first" [(ngModel)]="activeVariableName">
    <input type="radio" [value]="second" [(ngModel)]="activeVariableName">