映射没有值的组件属性 [英] Mapping component attributes without a value

查看:83
本文介绍了映射没有值的组件属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为Angular组件提供属性.属性"是指您在HTML中放入的切换样式布尔型属性,但未指定该属性的值:

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

如果存在 compact ,则组件应将其值强制为布尔值:

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?
  1. <my-component compact="compact"> // <= true
  2. <my-component compact="true> // <= true
  3. <my-component compact="false"> // <= true?

如果 compact 没有值,则它映射为true:

If compact has no value then it maps to true:

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

如果缺少 compact :

  1. < my-component> //< =假
  1. <my-component> // <= false

但是,当我不使用任何属性值时,该组件将显示为空,因此即使在构造函数中提供了默认值,我也无法区分情况4和情况5.

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〜4中, compact 的值的类型始终为字符串.

In case #1~4, the type of compact's value will always be string.

在案例4中, compact 的值为空字符串( string 的类型),而案例#5将为null ( object 的类型),因此您可以通过 typeof(compact)区分案例#4和#5.

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

这篇关于映射没有值的组件属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆