如何在Angular中动态改变绑定变量?
How to change bound variable dynamically in Angular?
我想,大家都知道,插值是如何工作的,我们可以很容易地对单个变量进行插值(可能这个解释不完全正确,但你会明白我的意思什么时候看看代码)。但是如果我们想在两个不同的变量之间动态切换呢?例如,我们有两个 class 属性:
public first: string = '"first" variable activated';
public second: string = '"second" variable activated';
并且有两个单选按钮,绑定到activeVariableName
class 属性:
<input type="radio" value="first" [(ngModel)]="activeVariableName">
<input type="radio" value="second" [(ngModel)]="activeVariableName">
我们可以这样插值:
<h1>{{activeVariableName}}</h1>
但是这样,我们将只看到 first 或 second,它们是 class 个属性名称。
所以我的问题是:"How to display values of this properties, but not just names?"
这是一个STACKBLITZ
您错过了绑定括号 []
,因此值为 first
和 second
。尝试:
<input type="radio" [value]="first" [(ngModel)]="activeVariableName">
<input type="radio" [value]="second" [(ngModel)]="activeVariableName">
我想,大家都知道,插值是如何工作的,我们可以很容易地对单个变量进行插值(可能这个解释不完全正确,但你会明白我的意思什么时候看看代码)。但是如果我们想在两个不同的变量之间动态切换呢?例如,我们有两个 class 属性:
public first: string = '"first" variable activated';
public second: string = '"second" variable activated';
并且有两个单选按钮,绑定到activeVariableName
class 属性:
<input type="radio" value="first" [(ngModel)]="activeVariableName">
<input type="radio" value="second" [(ngModel)]="activeVariableName">
我们可以这样插值:
<h1>{{activeVariableName}}</h1>
但是这样,我们将只看到 first 或 second,它们是 class 个属性名称。
所以我的问题是:"How to display values of this properties, but not just names?"
这是一个STACKBLITZ
您错过了绑定括号 []
,因此值为 first
和 second
。尝试:
<input type="radio" [value]="first" [(ngModel)]="activeVariableName">
<input type="radio" [value]="second" [(ngModel)]="activeVariableName">