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" [disabled]="disabledMas"></button>
button.component.ts
disabledMas = true;
@Input('disabledMas')
get masDisabled(): boolean {
return this.disabledMas;
}
set masDisabled(value: boolean) {
this.disabledMas = value === false;
}
CodePudding user response:
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';
}