简体   繁体   English

Angular 对用于属性绑定的模板参考变量的更改检测

[英]Angular change detection on Template Reference Variables for property binding

I'm playing around with template reference variables.我在玩模板引用变量。 And thought of using its value to set the disabled property on a button.并考虑使用它的值来设置按钮上的 disabled 属性。 ie disable a button unless the input field is non-empty.即禁用按钮,除非输入字段为非空。 I expected the following code to work but the button stays disabled even after some value is entered in the input.我希望下面的代码可以工作,但即使在输入中输入了一些值,按钮也会保持禁用状态。

Why does Angular change detection not work in this case?为什么 Angular 变化检测在这种情况下不起作用?

Is there another way to do achieve this using ONLY template reference variables?是否有另一种方法可以仅使用模板引用变量来实现这一目标?

The code is written in Angular 8 and node 12.16.2代码写在 Angular 8 和节点 12.16.2

<div class="form-group col-md-6">
    <input #hello type="text" class="form-control" id="01">
</div>
<div class="form-group col-md-6">
    <button class="btn btn-primary" [disabled]="hello.value.length === 0">Deactivate</button>
</div>

You can try ngForm combined with ngModel directive to achieve this,您可以尝试ngForm结合ngModel指令来实现这一点,

<form #testForm="ngForm">
    <div class="form-group col-md-6">
        <input type="text" name="hello" ngModel class="form-control" id="01">
    </div>
    <div class="form-group col-md-6">
        <button class="btn btn-primary" [disabled]="testForm.value.hello.length === 0">
            Deactivate
        </button>
    </div>
</form>

{{testForm.value|json}}

Demo: https://stackblitz.com/edit/angular-ivy-xtdm4k?file=src/app/app.component.html演示: https://stackblitz.com/edit/angular-ivy-xtdm4k?file=src/app/app.component.html

For more details, see this .有关更多详细信息,请参阅

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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