【问题标题】:How to pass a string value to a component in angular2如何将字符串值传递给angular2中的组件
【发布时间】:2016-07-13 05:09:06
【问题描述】:

我想将字符串值传递给 angular2 中的组件,但它不适用于默认绑定。 我正在考虑类似的事情:

<component [inputField]="string"></component>

不幸的是,赋值右侧只允许使用表达式。有没有办法做到这一点?

【问题讨论】:

    标签: angular angular2-template


    【解决方案1】:

    要在字符串文字中包含单引号(可能还有其他特殊的 HTML 字符),第一个选项有效,而使用单引号包裹文字的选项会因解析错误而失败。例如:

    <component inputField="John&#39;s Value"></component>
    

    会正确输出“John's Value”。

    【讨论】:

      【解决方案2】:

      字符串字面量可以通过不同的方式传递:

      <component inputField="string"></component>
      <component [inputField]="'string'"></component>
      <component inputField="{{'string'}}"></component>
      

      【讨论】:

      • 它们之间有什么区别吗?例如。 Angular 会在最后两种情况下创建“绑定”还是足够聪明?
      • Angular 足够聪明。只有第一个在 DOM 中可见。
      • 谢谢。我在传递时没有嵌套引号,它返回的值为 NaN:&lt;component [inputField]='string'&gt;&lt;/component&gt;
      • 从技术上讲,我不建议使用选项 1 和 3。这实际上将包括组件元素上的那些属性和值,以及组件中可能使用这些值的任何元素。在示例中,id="example-id" 将传递所需的正确字符串,但是,现在将有 2 个元素具有相同的 id 属性。明智地使用这种方法...
      【解决方案3】:

      您可以通过将字符串括在引号中来传递字符串

      <component [inputField]="'string'"></component>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-10-08
        • 1970-01-01
        • 1970-01-01
        • 2018-07-11
        • 1970-01-01
        • 1970-01-01
        • 2016-10-25
        • 2017-08-23
        相关资源
        最近更新 更多