Mapping component attributes without a value

点点圈 提交于 2021-01-27 12:10:39

问题


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


回答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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!