【问题标题】:TypeScript - Angular: Multiline stringTypeScript - Angular:多行字符串
【发布时间】:2016-05-15 12:05:43
【问题描述】:

我是 Angular 2 初学者,我已经在我的 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;
    }
}

当我转到浏览器“显示 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;
    }
}

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

Uncaught TypeError: Cannot read property 'split' of undefined

【问题讨论】:

标签: typescript angular


【解决方案1】:

仅当我们希望在字符串中添加 \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

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

【讨论】:

    【解决方案2】:

    使变量如下

    firstName ='';
    lastName = '';
    

    【讨论】:

      【解决方案3】:

      这个呢?这将解决新行中的空白。但可能有点不可读并且会影响性​​能。

          let myString =
            `multi${""
            }line${""
            }string`;
      

      【讨论】:

        【解决方案4】:

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

        var myString = `abc
        def
        ghi`;
        

        【讨论】:

        • 它适用于我的地方....但是为什么不能像其他语言一样使用通常的 '' 呢?例如 JS 本身...
        • 如何忽略空格和换行符?
        • 对不起,我不明白这个问题。如果您不想要它们,为什么要首先添加它们。我不明白你要解决什么问题。
        • 这与我的回答相反。我认为这需要'a b c' + 'd e f'
        猜你喜欢
        • 2017-06-23
        • 2018-05-15
        • 2017-08-30
        • 1970-01-01
        • 1970-01-01
        • 2022-11-22
        • 2013-10-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多