简体   繁体   中英

How to add new line in string in Typescript - Angular 8

I am trying to implement in typescript the following:

this.comments = this.comment1 + '/n' + this.comment2

in HTML it is bound as {{comments}} .

It should print:

comment1
comment2

but it prints:

comment1/ncomment2

I have tried <br\\> too but it does not work. How to do it?

You can use the innerHTML and innerText directives in any template element for that. Like:

TS

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Hello<br>World';
  weather = 'Super\nsunny\nday';
}

HTML

<div [innerHTML]="name"></div>
<div [innerText]="weather"></div>

Demo for your reference: https://stackblitz.com/edit/angular-chusrl

您需要使用“\\n”而不是“/n”

you can try this by using es6 feature template string:-

this.comments = `${this.comment1}
${this.comment2}`;

When you are using typescript then you should use es6 features to leverage more functionality in code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM