In ES6, there is Template String feature, that is, we can form/concat string like this (with backtick)
const name = 'John';
const intro = `My name is ${name}`;
console.log(intro);
And in Angular 2 Component Template, we have double-curly braces of interpolation, which we can use to insert a value from a variable.
@Component({
selector: 'selector-test-tag',
template: `
<div>
<p>My name is ${name}</p>
<p>My name is {{name}}</p>
</div>
`
})
export class Test {
name: string;
}
Question: Are there any reason why choose one over the other one?
Displaying values with interpolationlink Interpolation refers to embedding expressions into marked up text. By default, interpolation uses the double curly braces {{ and }} as delimiters. Angular replaces currentCustomer with the string value of the corresponding component property.
To get started using template reference variables, simply create a new Angular component or visit an existing one. To create a template reference variable, locate the HTML element that you want to reference and then tag it like so: #myVarName .
Template strings (or Template literals ) in Typescript are multi-line string literals that allow string interpolation. String interpolation allows us to include embedded expressions as part of the string. Template strings allows us to create multi-line strings, basic string formatting & tagged templates.
In Angular, template expressions are computations or assignments done in the template inside the interpolation curly braces. This expression is considered as local and only exist inside the template. A template statement responds to an event raised by a binding target such as an element, component, or directive.
They are different things:
${}
are used as placeholders in a template string, as you already know. These template strings are not the same as Angular's templates and you shouldn't use ${}
in your Angular 2 templates. For starters, it won't work if you move the template to an external file.
{{}}
is Angular's interpolation syntax and it's what you want to use in Angular 2 templates. You define a property or a method in a component class and use {{}}
in the component's template to interpolate the value of that property or to call the method. You can also use expressions ({{a + b / 2}}
) and pipes ({{title | uppercase}}
).
A couple of resources:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
https://angular.io/docs/ts/latest/guide/template-syntax.html#!#interpolation
Good luck!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With