如何将字符串值传递给angular2中的组件

How to pass a string value to a component in angular2

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

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

不幸的是,赋值的右侧只允许使用表达式。有办法吗?

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

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

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

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

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

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

将正确输出"John's Value"。