TypeScript - Angular: 多行字符串

27 浏览
0 Comments

TypeScript - Angular: 多行字符串

我是一个Angular 2的初学者,我在我的dev/app.component.ts中写了这段代码:

import {Component} from 'angular2/core';
@Component({
    selector: 'my-app',
    template: '

{{contact.firstName}} {{contact.lastName}}

' }) 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: `

{{contact.firstName}} {{contact.lastName}}

` }) 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

0
0 Comments

在上述代码中,出现了一个问题:如何使用TypeScript和Angular创建多行字符串。代码中使用了数组的`join`方法来将多行字符串连接起来,但默认情况下,`join`方法使用逗号`,`来分隔字符串。因此,需要使用`.join("")`来确保字符串之间没有任何分隔符。

解决方法是将`.join(" ")`替换为`.join("")`,这样就可以得到所需的多行字符串。

以下是解决方法的代码示例:

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

使用这种方法,可以在TypeScript和Angular中创建多行字符串,而不会有任何分隔符的问题。这是一种简洁的解决方案,可以在代码中构建xpath选择器。

需要注意的是,`join`方法的默认分隔符是逗号,因此在使用`join`方法连接字符串时,可能需要显式地指定分隔符。在本例中,使用空字符串作为分隔符来确保字符串之间没有任何分隔符。

希望这篇文章对您理解TypeScript和Angular中多行字符串的创建有所帮助。

0
0 Comments

在TypeScript中,当我们想要在字符串中添加换行符时,一种常用的方法是使用反斜杠加上换行符"\n"。然而,如果我们只想在长字符串中换行而不添加"\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

需要注意的是,在下一行(示例中的第二行)的开头不要添加任何制表符或空格,否则可能会导致字符串格式错误。

通过在每行末尾添加反斜杠"\\",我们可以在TypeScript中实现多行字符串的效果。这种方法非常简便,适用于需要在字符串中换行而不添加"\n"的情况。

0
0 Comments

TypeScript - Angular: Multiline string问题的出现原因是使用单引号('')无法实现多行字符串,而使用反引号(``)可以实现多行字符串。这是因为在JavaScript中,反引号可以用于模板字符串,可以跨越多行,而单引号只能用于普通字符串,不能跨越多行。

解决方法是将需要多行的文本用反引号包裹起来,例如:

var myString = `abc
def
ghi`;

另外,有用户提问如何忽略空格和换行符。对此,有人建议在代码中添加换行符只是为了让代码看起来更整齐,但并不希望字符串本身包含额外的空格和换行符。对于这种情况,有人建议使用单引号拼接字符串,例如:

'a b c' + 'd e f'

这样可以避免在字符串中包含多余的空格和换行符。

另外,还有用户问如何在多行字符串中绑定变量。对此,有人建议使用模板字符串的插值功能,例如:

`Hello, ${name}!`

这样可以在多行字符串中动态地插入变量的值。

解决TypeScript - Angular: Multiline string问题的方法是使用反引号(``)来表示多行字符串,并可以使用模板字符串的插值功能来动态地绑定变量。

0