[英]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. 问题:这行得通,但是我必须在我的component.ts文件中声明
confirmationText
,并且只能在模板中使用它,所以我正在寻找一种在组件的模板中声明它的方法,以便保留我的组件类清洁。
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. 请注意,必须在输入元素上设置
ngModel
指令,以使其起作用。
<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 看我的解决方案
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.