简体   繁体   中英

Declare variable in template in Angular 2

I want give my users an opportunity to choose which type of input to use to select color: type='text' or type='color' . So, I wrote this template:

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

And in my-component.ts :

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

My question is: is it allright to declare colorInputTypeText as a field of MyComponent class, or I should declare it somehow locally in template? If the right answer is "in template", how to do that?

Thanks.

There isn't a problem to declare a field in a class as you did.

But, if you don't want to touch your class, you can do it only in the template:

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

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

Angular creates a colorInputTypeText for you under the hood.

The colorInputTypeText is a boolean variable. By default it's false , so the the checkbox is unchecked. If you want the default value equals true , you have to add the checked attribute like this:

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

Personally I prefer this solution because your class don't need to declare an extra property and the logic in the template is easy to understand.

Note: this answer was inspired by @Bernardo Pacheco, so please, don't forget to upvote his answer.

Here is the solution:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM