Disable button in angular with two conditions?
HtmlAngularTypescriptHtml Problem Overview
Is this possible in angular ?
<button type="submit" [disabled]="!validate && !SAForm.valid">Add</button>
I expect that if both of the conditions are true they will enable the button.
I've already tried the above code but it's not working as expected.
Html Solutions
Solution 1 - Html
It sounds like you need an OR instead:
<button type="submit" [disabled]="!validate || !SAForm.valid">Add</button>
This will disable the button if not validate or if not SAForm.valid.
Solution 2 - Html
In addition to the other answer, I would like to point out that this reasoning is also known as the De Morgan's law. It's actually more about mathematics than programming, but it is so fundamental that every programmer should know about it.
Your problem started like this:
enabled = A and B
disabled = not ( A and B )
So far so good, but you went one step further and tried to remove the braces.
And that's a little tricky, because you have to replace the and
/&&
with an or
/||
.
not ( A and B ) = not(A) OR not(B)
Or in a more mathematical notation:
I always keep this law in mind whenever I simplify conditions or work with probabilities.
Solution 3 - Html
Declare a variable in component.ts and initialize it to some value
buttonDisabled: boolean;
ngOnInit() {
this.buttonDisabled = false;
}
Now in .html or in the template, you can put following code:
<button disabled="{{buttonDisabled}}"> Click Me </button>
Now you can enable/disable button by changing value of buttonDisabled
variable.
Solution 4 - Html
> Is this possible in angular 2?
Yes, it is possible.
> If both of the conditions are true, will they enable the button?
No, if they are true, then the button will be disabled. disabled="true"
.
> I try the above code but it's not working well
What did you expect? the button will be disabled when valid
is false and the angular formGroup
, SAForm
is not valid.
A recommendation here as well, Please make the button of type button not a submit because this may cause the whole form to submit and you would need to use invalidate
and listen to (ngSubmit)
.
Solution 5 - Html
I use the ternary operator, but compare if form.valid
is true.
Ej:
<button mat-button color="primary" [disabled]="((formUser.valid==true) && (formColaborador.valid==true))? false:true" (click)="addClick()">Crear</button>
Solution 6 - Html
Using the ternary operator is possible like following.[disabled] internally required true or false for its operation.
<button type="button"
[disabled]="(testVariable1 != 0 || testVariable2!=0)? true:false"
mat-button>Button</button>