typescript 类型脚本-Angular :多行字符串

bwleehnv  于 2023-03-13  发布在  TypeScript
关注(0)|答案(4)|浏览(180)

我是一个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;
    }
}

它的工作,当我去浏览器“马克斯布朗显示”。
现在,我想在不同的行中编写模板部件,如下所示:

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
jljoyd4f

jljoyd4f1#

用```(反勾号)代替单引号'将文本换行,这样它就可以跨多行。

var myString = `abc
def
ghi`;
1cosmwyk

1cosmwyk2#

接受的答案只有当我们想在字符串中添加\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

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

von4xj4u

von4xj4u3#

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

vfhzx4xs4#

这个怎么样?这可以解决新行中的空格问题。但是可能有点不可读,并且会影响性能。

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

相关问题