How to pass a string value to a component in angular2

AngularAngular2 Template

Angular Problem Overview


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?

Angular Solutions


Solution 1 - Angular

String literals can be passed in different ways:

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

Solution 2 - Angular

You can pass a string by enclosing the string in quotes

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

Solution 3 - Angular

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAndras HatvaniView Question on Stackoverflow
Solution 1 - AngularGünter ZöchbauerView Answer on Stackoverflow
Solution 2 - AngularEric MartinezView Answer on Stackoverflow
Solution 3 - AngularGlennView Answer on Stackoverflow