Disable button in angular with two conditions?

后端 未结 5 1660
礼貌的吻别
礼貌的吻别 2020-12-25 09:31

Is this possible in angular ?


相关标签:
5条回答
  • 2020-12-25 10:09

    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.

    0 讨论(0)
  • 2020-12-25 10:19

    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>
    
    0 讨论(0)
  • 2020-12-25 10:21

    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.

    0 讨论(0)
  • 2020-12-25 10:27

    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).

    0 讨论(0)
  • 2020-12-25 10:30

    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.

    0 讨论(0)
提交回复
热议问题