user776686
user776686

Reputation: 8655

Mapping component attributes without a value

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:

  1. <my-component compact="compact"> // <= true
  2. <my-component compact="true> // <= true
  3. <my-component compact="false"> // <= true?

If compact has no value then it maps to true:

  1. <my-component compact> // <= true

If compact is missing out:

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

Upvotes: 5

Views: 2150

Answers (1)

Pengyy
Pengyy

Reputation: 38171

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

Upvotes: 4

Related Questions