简体   繁体   中英

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. 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?

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

<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,

<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

For more details, see this .

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