简体   繁体   中英

Angular - Declare variable within component template

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

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.

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

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