【问题标题】:How to disable button if there is no input entered including space char in Angular如果在Angular中没有输入包括空格字符在内的输入,如何禁用按钮
【发布时间】:2019-02-27 16:59:29
【问题描述】:

我有一个简单的输入字段和 1 个按钮来保存它。如果输入字段为空,则按钮变为禁用状态。但是使用我的代码,空格字符就像普通字符一样,因此用户可以通过放置空格来输入值。如何检查输入字段中至少存在 1 个字符?

代码:

<mat-form-field fxFlex="50">
            <input matInput name="postalAddress"
                   [(ngModel)]="employee.postalAddress" placeholder="Postal Address"
                   required>
</mat-form-field>

 <button type="button" id="save" class="button-style" (click)="onSaveOffice()"
                [disabled]="!employee.postalAddress" > Save
 </button>

注意:我在后面使用 typescript,所以我需要在 typescript 代码中做任何逻辑吗?

【问题讨论】:

    标签: javascript html angular typescript


    【解决方案1】:

    你可以在检查空之前对字符串使用trim()方法,这样它会删除所有的空格:

    <mat-form-field fxFlex="50">
                <input matInput name="postalAddress"
                       [(ngModel)]="employee.postalAddress" placeholder="Postal Address"
                       required>
    </mat-form-field>
    
     <button type="button" id="save" class="button-style" (click)="onSaveOffice()"
                    [disabled]="!employee.postalAddress?.trim()" > Save
     </button>
    

    希望对您有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多