2

I have to disable/enable a button based on the value from a textbox.

This is how I do it currently

<input [(ngModel)]="confirmationText" type='text'>
<button [disabled]="confirmationText != 'yes'">Delete</button>

The problem: This works, but I have to declare confirmationText in my component.ts file and I use it only in the template, So I'm looking for a way to declare it within the component's template so that I can keep my component class clean.

Stackblitz

0

2 Answers 2

5

You can use a template reference variable to achieve what you want. Please note that the ngModel directive must be set on the input element in order to make it work.

<input #textInput type="text" ngModel>
<button [disabled]="textInput.value !== 'yes'">Delete</button>

See this stackblitz for a demo.

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

2 Comments

I was about to publish my answer than i got update that you already did. Thats correct.
The ngModel directive is what I missed, Thanks :)
0

you must get the value in the template reference like this

<input [(ngModel)]="confirmationText" type='text' #myInput> <button [disabled]="myInput.value != 'yes'">Delete</button>

look at my solution

stackblitz

2 Comments

Thanks for the answer, but without the ngModel directive, it doesn't work, for example, try this <input type='text' #myInput>
@cyberpirate92 - This answer should work because the ngModel directive is set in the input element. However, it involves the declaration of confirmationText in the component class, which is what you want to avoid.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.