How can I properly write a multi-line string for the template in TypeScript for Angular?

In Angular 2 with TypeScript, I’m trying to format the template part of my component into multiple lines.

Here’s my current code:

import { Component } from 'angular2/core';

@Component({
    selector: 'my-app',
    template: '<h3 (click)="onSelect()"> {{contact.firstName}} {{contact.lastName}}</h3>'
})
export class AppComponent {
    public contact = {firstName: "Max", lastName: "Brown", phone: "3456732", email: "max88@gmail.com"};
    public showDetail = false;
    onSelect() {
        this.showDetail = true;
    }
}

This works fine, displaying “Max Brown” in the browser. However, I want to write the template part on different lines like this:

import { Component } from 'angular2/core';

@Component({
    selector: 'my-app',
    template: '<h3 (click)="onSelect()">\n    {{contact.firstName}} {{contact.lastName}}\n</h3>'
})
export class AppComponent {
    public contact = {firstName: "Max", lastName: "Brown", phone: "3456732", email: "max88@gmail.com"};
    public showDetail = false;
    onSelect() {
        this.showDetail = true;
    }
}

When I do this, I get an error in the Chrome console: Uncaught TypeError: Cannot read property ‘split’ of undefined. How can I properly write a multi-line string for the template in TypeScript for Angular?

To handle multi-line strings in TypeScript, use backticks (`) instead of single quotes ('). For example:

var myString = `abc
def
ghi`;

This way, the string can span multiple lines without issues.

If you want to write a multi-line string in TypeScript without adding actual newline characters (\n), you can escape the new lines with a backslash ().

For example:

let firstName = `this is line 1 \
and this is line 2 => yet "new line" are not \
included because they were escaped with a "\"`;

console.assert(firstName === 'this is line 1 and this is line 2 => yet "new line" are not included because they were escaped with a "\"'); // true

Note: Ensure that no tabs or spaces are added at the beginning of the continued lines.

To create a multi-line string in JavaScript or TypeScript, you can use the join method on an array of strings.

For example:

const multiLineString = [
  "I wish",
  "there were a better way",
  "to do this!"
].join(" ");

This approach is clean and effective for building strings, such as XPath selectors, in your code. Note: By default, the join method separates strings with a comma ,. If you don’t want any separator, use .join(“”).