101

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?

3 Answers 3

207

String literals can be passed in different ways:

<component inputField="string"></component>
<component [inputField]="'string'"></component>
<component inputField="{{'string'}}"></component>
Sign up to request clarification or add additional context in comments.

4 Comments

Is there any difference between those? E.g. would Angular create "bindings" in the last two cases or it's smart enough?
Angular is smart enough. Only the first one will be visible in the DOM.
Thanks. I was passing without nested quotes and it was returning the value as NaN: <component [inputField]='string'></component>
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...
53

You can pass a string by enclosing the string in quotes

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

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.