在 Angular 2 中的模板中声明变量

Declare variable in template in Angular 2

我想让我的用户有机会选择使用哪种类型的输入 select 颜色:type='text'type='color'。所以,我写了这个模板:

 <input [type]="colorInputTypeText ? 'text' : 'color'">
 <input type="checkbox" [(ngModel)]="colorInputTypeText" name="colorInputTypeText">

并且在 my-component.ts 中:

@Component({
    ...
})
export class MyComponent {
    colorInputTypeText = true;
    ...
}

我的问题是: 是否可以将 colorInputTypeText 声明为 MyComponent class 的字段,或者我应该以某种方式声明它在模板中本地?如果正确答案是"in template",如何做?

谢谢。

像您一样在 class 中声明字段没有问题。

但是,如果您不想触摸您的 class,您只能在模板中进行操作:

<input [type]="colorInputTypeText ? 'text' : 'color'">

<input type="checkbox" name="colorInputTypeText" #cb (change)="colorInputTypeText = cb.checked">

Angular 在后台为您创建一个 colorInputTypeText

colorInputTypeText 是一个布尔变量。默认情况下它是 false,因此未选中该复选框。如果您希望默认值等于 true,则必须像这样添加 checked 属性:

<input type="checkbox" name="colorInputTypeText" checked #cb (change)="colorInputTypeText = cb.checked">

我个人更喜欢这个解决方案,因为你的 class 不需要声明额外的 属性 并且模板中的逻辑很容易理解。

注意:此答案的灵感来自@Bernardo Pacheco,所以请不要忘记为他的答案点赞。

解决方法如下:

<input [type]="cb.checked ? 'color' : 'text'" id="color" name="color">
<input type="checkbox" name="inputTypeColor" checked #cb [(ngModel)]="cb.checked">