簡體   English   中英

TypeScript - Angular:多行字符串

[英]TypeScript - Angular: Multiline string

我是 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

將文本包裹在` (反引號)而不是單引號'中,然后它可以跨越多行。

var myString = `abc
def
ghi`;

僅當我們希望在字符串中添加 \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

注意 - 確保您沒有在下一行(示例中的第二行)開頭添加任何制表符和空格

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

那這個呢? 這將解決新行中的空白。 但可能有點不可讀並且會對性能產生影響。

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

使變量如下

firstName ='';
lastName = '';

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM