Angular2: difference between $ {..} and {{...}} in the pattern line

In ES6, there is a Template String function, that is, we can form / concatenate a string as follows (with a reverse tag)

const name = 'John'; const intro = 'My name is ${name}'; console.log(intro); 

And in the Angular 2 Component template, we have double braces for interpolation, which we can use to insert values ​​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. Is there a reason you choose one from the other?

+13
source share
2 answers

These are different things:

${} used as placeholders in the template string, as you already know. These pattern strings do not match Angular patterns, and you should not use ${} in your Angular 2 patterns. Firstly, this will not work if you move the pattern to an external file.

{{}} is the Angular interpolation syntax, and this is what you want to use in Angular 2 templates. You define a property or method in the component class and use {{}} in the component template to interpolate the value of this property or call the method. You can also use expressions ( {{a + b / 2}} ) and pipes ( {{title | uppercase}} ).

Several 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

+19
source

The Angular expression {{ }} creates a binding that is controlled by angular, where Angular automatically tracks property changes and can dynamically change the value of the property as it changes at run time, while the ES6 template method parses the value once, at the first render.

+5
source

Source: https://habr.com/ru/post/1259253/


All Articles