【问题标题】:Set boolean input property via attribute presence on directive通过指令上的属性存在设置布尔输入属性
【发布时间】:2018-06-02 05:50:16
【问题描述】:

我可以将输入属性添加到指令并通过传递值来设置它

<my-component [customInput]='true'></my-component>

但是对于布尔输入属性,我无法弄清楚如何通过指令上输入的存在/不存在来设置值。即

<my-component customInput></my-component>

当我尝试此操作时,customInput 未设置,而我希望将其设置为 true。有什么想法可以做到这一点吗?谢谢!

【问题讨论】:

    标签: angular


    【解决方案1】:

    原来存在但没有值的输入属性(即&lt;my-component customInput&gt;&lt;/my-component&gt;)设置为空字符串""

    所以 &lt;my-component customInput&gt;&lt;/my-component&gt; 只要我在输入中添加一个 setter 函数来强制该值,就可以工作。类似的东西

    @Input() customInput(value: string | boolean) {
      if (typeof value === 'string' {
        this._customInput = true;
      }
      else {
        this._customInput = value;
      }
    }
    

    我还要注意,使用没有像 &lt;my-component [customInput]&gt;&lt;/my-component&gt; 这样的值的输入绑定会导致 customInput 未被设置。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-12
      • 2016-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-14
      相关资源
      最近更新 更多