98

I'd like to pass a string value to a component in angular2, but it doesn't work with the default binding. I'm thinking of something similar to this:

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

Unfortunately, only expressions are allowed on the right side of the assignment. Is there a way to do this?

Andras Hatvani
  • 4,346
  • 4
  • 29
  • 45

3 Answers3

205

String literals can be passed in different ways:

<component inputField="string"></component>
<component [inputField]="'string'"></component>
<component inputField="{{'string'}}"></component>
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • 2
    Is there any difference between those? E.g. would Angular create "bindings" in the last two cases or it's smart enough? – Alexander Abakumov Oct 26 '17 at 21:24
  • Angular is smart enough. Only the first one will be visible in the DOM. – Günter Zöchbauer Oct 27 '17 at 03:03
  • 2
    Thanks. I was passing without nested quotes and it was returning the value as NaN: `` – Eric Soyke Feb 07 '18 at 16:47
  • Technically, I wouldn't suggest options 1 and 3. This will literally include those attributes and values on the component element as well as any elements within the component that may utilize those values. In example `id="example-id"` will pass the correct string desired, however, now there will be 2 elements with the same `id` attribute. Use this approach wisely... – mrtpain Feb 16 '19 at 04:37
53

You can pass a string by enclosing the string in quotes

<component [inputField]="'string'"></component>
Eric Martinez
  • 31,277
  • 9
  • 92
  • 91
3

To include a single quote (and possibly other special HTML characters) in the string literal the first option works while those that use single quotes to wrap the literal fail with parse errors. For example:

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

Will output "John's Value" correctly.

Glenn
  • 688
  • 10
  • 16