【问题标题】:Angular change detection on Template Reference Variables for property binding用于属性绑定的模板引用变量的角度变化检测
【发布时间】:2021-06-22 22:06:09
【问题描述】:

我在玩模板引用变量。并考虑使用它的值来设置按钮上的 disabled 属性。即禁用按钮,除非输入字段为非空。我希望下面的代码能够工作,但即使在输入中输入了一些值后,该按钮也会保持禁用状态。

为什么 Angular 变化检测在这种情况下不起作用?

还有其他方法可以仅使用模板引用变量来实现吗?

代码是用 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>

【问题讨论】:

    标签: javascript angular typescript dom


    【解决方案1】:

    你可以尝试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}}
    

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

    更多详情请见this

    【讨论】:

      猜你喜欢
      • 2019-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-11
      • 1970-01-01
      • 1970-01-01
      • 2018-12-22
      • 1970-01-01
      相关资源
      最近更新 更多