0

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.

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

what is init value for colorInputTypeTextin this case? can I modify it?
This doesn't 100% work. Before I first time check/uncheck checkbox, colorInputTypeText is undefined, so it become initialised and works only after 1st click on checkbox.
undefined in javascript is a falsy value, so the checkbox is unchecked. If you want to initialize with a true value you have to add the checked attribute in the input field as I said.
But it isn't set to true until change event occurs. Anyway, you inspired me to improve your answer to make it work. Check it out.
2

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">

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.