0

I'm trying to create a reusable component. My expectation is that the value of masDisabled when not set to false or true will always be true. I still want the masDisabled construct like that, not [masDisabled]. But I have a problem, all components that do not have the masDisabled property are also disabled. How to solve it?

test.component.html

<mas-button masDisabled></mas-button>

button.component.html

<button type="button" class="btn btn-primary" [disabled]="disabledMas"></button>

button.component.ts

disabledMas = true;

@Input('disabledMas')
get masDisabled(): boolean {
    return this.disabledMas;
}
set masDisabled(value: boolean) {
    this.disabledMas = value === false;
}
2
  • when i set disabledMas = false; and also set this.disabledMas = value === true; All button components will be active, including those with the masDisabled property Commented Sep 15, 2022 at 0:33
  • so where should I set undefined? in get or set? Commented Sep 15, 2022 at 0:52

1 Answer 1

1

You are using the wrong attribute name. You can see in this StackBlitz that your getter and setter are not even being hit!

In your component, it's called @Input('disabledMas'), but in your component template, you use a different name <mas-button masDisabled></mas-button>.

Once you correct that, you'll see an error if you don't set a boolean value, so you should do it like this:

<mas-button [disabledMas]="true"></mas-button>

Here's a working StackBlitz.


It doesn't seem like you really need a getter and setter at all, I think something like this would work:

@Input() disabledMas = false; 
[disabled]="!disabledMas"

Here's a working StackBlitz demo.


EDIT:

Since you want your default (attribute not present) to be visible, we will default disabled to false.

Since you don't want to pass a value, the passed value will be an empty string. So, we can use the setter to compare with an empty string to determine if it's disabled:

  isDisabled = false;

  @Input() set masDisabled(value: string) {
    this.isDisabled = value === '' || value === 'true';
  }
Sign up to request clarification or add additional context in comments.

3 Comments

as I said before, the expectations I hope for do not use brackets, just masDisabled. I have tried the example from the following link stackoverflow.com/questions/52526796/…, but still failed
Okay, I think I get what you're going for, try this StackBlitz
Wow........ it's going well, thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.