TypeScript - Angular: สตริงหลายบรรทัด
ฉันเป็นผู้เริ่มต้น 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:"[email "};
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:"[email "};
public showDetail = false;
onSelect() {
this.showDetail=true;
}
}
แต่ฉันได้รับข้อผิดพลาดนี้ในคอนโซลของ Chrome:
Uncaught TypeError: Cannot read property 'split' of undefined
คำตอบ #1
ห่อข้อความด้วย ` (backticks) แทนที่จะใช้เครื่องหมายคำพูดเดี่ยว ' จากนั้นข้อความสามารถข้ามหลายบรรทัดได้
var myString = `abc
def
ghi`;
คำตอบ #2
คำตอบที่ยอมรับใช้งานได้เฉพาะกรณีที่เราต้องการให้ \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
หมายเหตุ - ตรวจสอบให้แน่ใจว่าคุณไม่ได้เพิ่มแท็บหรือช่องว่างใด ๆ ที่จุดเริ่มต้นของบรรทัดถัดไป (บรรทัดที่สองในตัวอย่าง)
คำตอบ #3
const multiLineString = [
"I wish",
"there were a better way",
"to do this!",
].join(" ");
