angularng-bootstrapangular17

NG Bootstrap modal disable a button in the modal's template


I'm using Angular 17 and ng-bootstrap 16 and I'm creating an ng-bootstrap modal. I have a Template in my component used as the content for the modal. What I want is to enable or disable the Save button in the modal when the one input element in the modal's form is blank. I disable the button by default and in the change event of the input I'm toggling the disabled state of the button. I can get it to enable the button when text is entered but it won't disable the button when I delete the text of the input. Below is the template.

<ng-template #getReportName let-modal>
    <div class="modal-header">
        <h4 class="modal-title" id="modal-basic-title">Report File Name</h4>
        <button type="button" class="btn-close" aria-label="Close" (click)="modal.dismiss('Cross click')"></button>
    </div>
    <div class="modal-body">
        <form #reportNameForm>
            <div class="mb-3">
                <label for="reportname">Report Name</label>
                <div class="input-group">
                    <input #reportInput
                        id="reportname"
                        class="form-control"
                        placeholder="Report Name"
                        name="filename"
            (change)="this.saveButton.disabled=(this.value==='')"
                    />
                </div>
            </div>
        </form>
    </div>
    <div class="modal-footer">
        <button #saveButton type="button" class="btn btn-outline-secondary" disabled="true" (click)="modal.close(reportInput.value)">Save</button>
    </div>
</ng-template>

Not sure what's going wrong.


Solution

  • You are not updating the inputted value from the #reportInput input to the value variable. You need to add [(ngModel)]="value" to the <input>.

    <input
      #reportInput
      id="reportname"
      class="form-control"
      placeholder="Report Name"
      name="filename"
      [(ngModel)]="value"
      (change)="saveButton.disabled = value ===''"
    />
    

    Alternatively, you may enable/disable the button by checking reportInput.value, without need to save the value to the value variable.

    <input
      #reportInput
      id="reportname"
      class="form-control"
      placeholder="Report Name"
      name="filename"
      (change)="saveButton.disabled = reportInput.value === ''"
    />
    

    Demo @ StackBlitz


    Aside, with (change) event, the Save button will be enabled/disabled once the value variable is updated/the input element is not focused. If you want the Save button to be immediately reflect for the disabled status (during the user is typing), you should look for (input) event.