带有打字稿的多行字符串 - Angular2

spl*_*unk 44 typescript angular

我是一个angular2初学者,我在dev/app.component.ts中编写了这段代码

import {Component} from 'angular2/core';

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

    public showDetail = false;
    onSelect() {
        this.showDetail=true;
    }
}
Run Code Online (Sandbox Code Playgroud)

当我进入浏览器"显示Max Brown"时,它可以工作.现在我想在不同的行上编写模板部分,如下所示:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

但我在Chrome控制台中收到此错误:

Uncaught TypeError: Cannot read property 'split' of undefined
Run Code Online (Sandbox Code Playgroud)

Gün*_*uer 120

将文本换行`(反引号)而不是单引号',然后它可以跨越多行.

var myString = `abc
def
ghi`;
Run Code Online (Sandbox Code Playgroud)

  • 似乎你可以使用常规报价http://stackoverflow.com/questions/805107/creating-multiline-strings-in-javascript.反引号也允许插值https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Template_literals (3认同)
  • 那将与我的答案相反。我认为这需要`'abc' + 'de f'` (3认同)
  • 如何忽略空格和新线? (2认同)

小智 23

仅当我们希望在字符串中添加 \n 时,接受的答案才有效,如果我们只想将内容放在换行符上而不在长字符串中添加 \n ,请在每行末尾添加 \ ,如下所示

string 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
Run Code Online (Sandbox Code Playgroud)

注意 - 确保您没有在下一行(示例中的第二行)的开头添加任何制表符和空格


Jay*_*ass 9

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

  • 这是在我的代码中构建 xpath 选择器的最简洁的解决方案。**注意:** * `join` 方法默认使用逗号 `','` 分隔字符串。* 您可能想要使用 `.join("")` 。 (4认同)