我知道在angular2中我可以禁用具有该
[disable]
属性的按钮,例如:
<button [disabled]="!isValid" (click)="onConfirm()">Confirm</button>
但我可以用[ngClass]
or来做[ngStyle]
吗?像这样:
<button [ngStyle]="{disabled : !isValid}" (click)="onConfirm()">Confirm</button>
谢谢。
我知道在angular2中我可以禁用具有该
[disable]
属性的按钮,例如:
<button [disabled]="!isValid" (click)="onConfirm()">Confirm</button>
但我可以用[ngClass]
or来做[ngStyle]
吗?像这样:
<button [ngStyle]="{disabled : !isValid}" (click)="onConfirm()">Confirm</button>
谢谢。
我在想。为什么不想使用[disabled]
Angular 2 提供的属性绑定?这是处理这种情况的正确方法。我建议您isValid
通过组件方法移动您的支票。
<button [disabled]="! isValid" (click)="onConfirm()">Confirm</button>
基本上你可以ngClass
在这里使用。但是添加类不会限制事件的触发。要在有效输入上触发事件,您应该将click
事件代码更改为以下。所以onConfirm
只有当字段有效时才会触发。
<button [ngClass]="{disabled : !isValid}" (click)="isValid && onConfirm()">Confirm</button>
我会推荐以下。
<button [disabled]="isInvalid()">Submit</button>
是的你可以
<div class="button" [ngClass]="{active: isOn, disabled: isDisabled}"
(click)="toggle(!isOn)">
Click me!
</div>
https://angular.io/docs/ts/latest/api/common/NgClass-directive.html
如果您有表格,那么以下也是可能的:
<form #f="ngForm">
<input name="myfield" type="text" minlenght="3" required ngModel>
<button type="submit" [disabled]="!f.valid">Submit</button>
</form>
此处演示: http://plnkr.co/edit/Xm2dCwqB9p6WygrquUGh?p=preview&open= app%2Fapp.component.ts
在 Angular2 中,使用ngClass
禁用无效表单的按钮并不是一个好的做法,因为它提供了内置功能来启用和禁用按钮,如果表单是有效的和无效的,而不需要做任何额外的努力/逻辑。
[disabled]
将执行所有操作,例如如果表单有效,那么它将被启用,如果表单无效,那么它将自动被禁用。
请参阅示例:
<form (ngSubmit)="f.form.valid" #f="ngForm" novalidate>
<input type="text" placeholder="Name" [(ngModel)]="txtName" name="txtname" #textname="ngModel" required>
<input type="button" class="mdl-button" [disabled]="!f.form.valid" (click)="onSave()" name="">
下面的代码可能会有所帮助:
<button [attr.disabled]="!isValid ? true : null">Submit</button>
我尝试使用禁用以及单击事件。下面是片段,接受的答案也很好用,我添加这个答案是为了举例说明它如何与禁用和单击属性一起使用。
<button (click)="!planNextDisabled && planNext()" [disabled]="planNextDisabled"></button>
我认为这是最简单的方法
<!-- Submit Button-->
<button
mat-raised-button
color="primary"
[disabled]="!f.valid"
>
Submit
</button>
如果您正在使用响应式表单并希望禁用与表单控件关联的某些输入,则应将此disabled
逻辑放入您的代码中并调用yourFormControl.disable()
或yourFormControl.enable()
<button [disabled]="this.model.IsConnected() == false"
[ngClass]="setStyles()"
class="action-button action-button-selected button-send"
(click)= "this.Send()">
SEND
</button>
.ts 代码
setStyles()
{
let styles = {
'action-button-disabled': this.model.IsConnected() == false
};
return styles;
}