问题
I am after providing a property for my Angular component. By property I mean a toggle-style boolean attribute that you put in HTML without specifying the attribute's value:
as opposed to an input (this is not what I want):
If compact
is present then the component should coerce its value it to a boolean:
<my-component compact="compact">
// <= true<my-component compact="true>
// <= true<my-component compact="false">
// <= true?
If compact
has no value then it maps to true:
<my-component compact>
// <= true
If compact
is missing out:
<my-component>
// <= false
However when I leave it without an attribute value, the component sees null, so I am not able to distinguish between case #4 and #5, even if I provide a default value within constructor.
constructor(
@Attribute('compact') public compact,
) {
console.log(this.compact) // `null` for <my-component compact>
}
How should I go about it? Is Attribute decorator alone capable
回答1:
In case #1~4, the type of compact
's value will always be string.
In case #4, the value of compact
is empty string(type of string
) while case #5 will be null(type of object
), so you can distinguish case #4 and #5 by typeof(compact)
.
来源:https://stackoverflow.com/questions/49026154/mapping-component-attributes-without-a-value