[英]how to enable or disable a button based on the inputs to the input fields
我有四個輸入 html 字段和一個按鈕。 我想要做的是,僅當每個輸入字段中有四個輸入時才使按鈕處於活動狀態並啟用。 如果至少有一個輸入字段為空,則必須禁用該按鈕
我想我需要在輸入字段中綁定一些屬性請讓我知道如何實現
代碼:
<div class="modal-body">
<form #form="ngForm" class="clr-form clr-form-horizontal" autocomplete="off">
<clr-input-container>
<label >{{ "DISTANCE_MEASUREMENT.START_LONGITUDE" | translate }}:</label>
<input
id="startLngTextId"
required
maxlength="25"
clrInput
type="text"
name="name"
[(ngModel)]=iMeasureDistanceParametersPasser.startLongitude
/>
</clr-input-container>
<clr-input-container>
<label>{{ "DISTANCE_MEASUREMENT.START_LATITUDE" | translate }}:</label>
<input
id="startLatTextId"
required
maxlength="25"
clrInput
type="text"
name="name"
[(ngModel)]=iMeasureDistanceParametersPasser.startLatitude
/>
</clr-input-container>
<clr-input-container>
<label>{{ "DISTANCE_MEASUREMENT.END_LONGITUDE" | translate }}:</label>
<input
id="endLngTextId"
required
maxlength="25"
clrInput
type="text"
name="name"
[(ngModel)]=iMeasureDistanceParametersPasser.endLongitude
/>
</clr-input-container>
<clr-input-container>
<label>{{ "DISTANCE_MEASUREMENT.END_LATITUDE" | translate }}:</label>
<input
id="endLatTextId"
required
maxlength="25"
clrInput
type="text"
name="name"
[(ngModel)]=iMeasureDistanceParametersPasser.endLatitude
/>
</clr-input-container>
<div>
<button
[disabled]="form.invalid"
class="btn btn-primary"
type="button"
(click)="measureDistanceForCoordinates()"
>
{{ "DISTANCE_MEASUREMENT.ENTRY_LABEL" | translate }}
</button>
</div>
<div>
<button
class="btn btn-primary"
type="button"
(click)="clearInputs()"
>
{{ "COMMON.CLEAR_DATA" | translate }}
</button>
</div>
<div>
<label *ngIf=showMeasuredDistance>
{{ "DISTANCE_MEASUREMENT.DISTANCE" | translate }}
{{ "DISTANCE_MEASUREMENT.EQUAL" | translate }}
{{ mMeasuredDistanceInKM }}
{{ "DISTANCE_MEASUREMENT.UNIT_KM" | translate }}
</label>
</div>
</form>
<div class="modal-footer">
<button
class="btn btn-outline"
type="button"
(click)="hideWindowOverlay()"
>
{{ "COMMON.CANCEL" | translate }}
</button>
</div>
</div>
angular 頁面上有教程
tldr;
<input name="property" required minlength="4"
[(ngModel)]="property" #ngModelVar="ngModel">
<button [disabled]="ngModelVar.invalid && (ngModelVar.dirty || ngModelVar.touched)">test</button>
然而,這不是做事的最佳方式。 請務必閱讀有關FormControl的信息。
我們在大型應用程序中做事的方式(真正的大型 forms 具有多個驗證條件等)是創建一個匹配[name][ngModel]
的指令。 然后我們在 construrcotr 中創建注入NgForm
的服務。 最后,當我們想在頁面上驗證我們的表單時,我們會詢問MyFormService
if this.myFormService.ngForm.valid
。
有很多事情要做,但事實證明這是一個很棒的概念。 只需少量工作,您就可以創建響應式模板驅動的 forms。
注意:您還應該始終讓用戶單擊按鈕,然后如果出現問題,請向他顯示彈出窗口為什么您不允許他執行操作。
編輯:
如果表單像這樣無效,您可以禁用按鈕(但按鈕必須在表單元素內)
<button [disabled]="form.invalid">test</button>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.