Is this possible in angular ?
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.
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>
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.
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)
.
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.