How do you add a line break (\n) to a string in TypeScript?

I'm having trouble adding a line break to a concatenated string like this:

- Item 1
- Item 2
var msg: string = '';
msg += '- Campo NOME é obrigatório';
msg += "\n- Campo EMAIL é obrigatório";

However, when I display the output, there is no line break:

- Item 1 - Item 2

I have researched extensively but have not yet found a solution. Can you please provide assistance? :)

Answer №1

When converting to HTML, ensure you utilize the appropriate tag for a new line :

If your source contains Hello\n\nTest, it will be displayed as:

Hello!

Test

For the string Hello<br><br>Test in your HTML source, it will appear like this:

Hello<br><br>Test

Give this a try:

var message: string = "";
message += "- Campo NOME is mandatory";
message += "<br/>- Campo EMAIL is mandatory";

Check out the demo here : https://jsfiddle.net/9fuxgbms/1/

Answer №2

Incorporating Angular 15 into my project has proven successful for me,

home.component.ts

headerText = "Hello, Please Input Your \n Name";

home.component.html

<div class="header">
  <h1>{{headerText}}</h1>
</div>

home.component.scss

.header {
    margin-top: 100px;

    h1 {
      white-space: break-spaces; // <===== This is crucial
    }
  }

Depending on your requirements, you may opt for either white-space: break-spaces; or white-space: pre-line;.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating Blobs with NSwag for multipart form data

The Swagger documentation shows that the endpoint accepts multipart form data and is able to receive form data from a client. However, the TypeScript client generated by NSwag appears to be unusable as it only accepts Blob. uploadDoc(content:Blob): Observ ...

Reversing the order of items in Angular 2 for repetition

Is there a way to display search items in reverse order? This is what I have attempted so far: let newSearchTerm = this.getItem(this.searchHistoryKey) newSearchTerm.push({ 'q': this.searchTerm }); this.setItem(this.searchH ...

Looking for a JavaScript library to display 3D models

I am looking for a JavaScript library that can create 3D geometric shapes and display them within a div. Ideally, I would like the ability to export the shapes as jpg files or similar. Take a look at this example of a 3D cube: 3d cube ...

Enhance your React Typescript High Order Component by incorporating additional properties and implementing them

I am in the process of creating a React HOC with specific requirements: It should take a component as input, modify the hidden property (or add it if necessary), and then return the updated component The rendered component should not display anything whe ...

Setting the value in an Autocomplete Component using React-Hook-Forms in MUI

My form data contains: `agreementHeaderData.salesPerson ={{ id: "2", name: "Jhon,Snow", label: "Jhon,Snow", value: "<a href="/cdn-cgi/l/email-prot ...

Divide the list of commitments into separate groups. Carry out all commitments within each group simultaneously, and proceed to the next group

My Web Crawling Process: I navigate the web by creating promises from a list of website links. These promises act as crawlers and are executed sequentially. For instance, if I have 10 links, I will crawl the first link, wait for it to complete, then move ...

Is it possible to deactivate the error message related to "Unable to ascertain the module for component..."?

I recently incorporated a new component into my TypeScript2+Angular2+Ionic2 project. Right now, I have chosen not to reference it anywhere in the project until it is fully developed. However, there seems to be an error thrown by Angular/ngc stating "Cannot ...

Discovering the complete URL utilized to load the application

I am working on an Angular application and I am looking to retrieve the full URL of the application from within the code - specifically, the complete address that the user entered into their browser to access the app. When using Router or ActivatedRoute i ...

Error encountered: Could not find the specified file or directory, 'resultsCapturer.js:.will-be-removed-after-cucumber-runs.tmp'

I'm currently working on automating an Angular 4 application. Whenever I execute "protractor config.js" SCENARIO 1: If the format option in my config.ts file looks like this: format: ['json:../reporting/results.json'] An error message is ...

Creating an enum from an associative array for restructuring conditions

Hey everyone, I have a situation where my current condition is working fine, but now I need to convert it into an enum. Unfortunately, the enum doesn't seem to work with my existing condition as mentioned by the team lead. Currently, my condition loo ...

Implementing recursive functionality in a React component responsible for rendering a dynamic form

Hello to all members of the Stack Overflow community! Presently, I am in the process of creating a dynamic form that adapts based on the object provided, and it seems to handle various scenarios effectively. However, when dealing with a nested objec ...

Having trouble with clearInterval in my Angular code

After all files have finished running, the array this.currentlyRunning is emptied and its length becomes zero. if(numberOfFiles === 0) { clearInterval(this.repeat); } I conducted a test using console.log and found that even though ...

What is the best way to integrate the retry functionality from Rxjs into my await function?

When calling an await function in my code block, if it fails on the first try, I need to retry it. If it fails again on the second try, I want to display an error message. BELOW IS MY CODE SNIPPET async makeCall(inputs: myInputs): Promise<Instance> ...

The process of linking a Json response to a table

In my products.components.ts class, I am retrieving Json data into the variable this.Getdata. ngOnInit() { this._service.getProducts(this.baseUrl) .subscribe(data => { this.Getdata=data this.products=data alert(JSON.stringify(this.Getdata)); ...

Required file missing in React application unable to locate

I have a project organized in the following way: - my-app - src - some files - public - index.html - ... When I run npm start, the application functions as expected. Now, I am looking to rename src to application! After renami ...

Discover the accurate `keyof` for a nested map in TypeScript

Here is the code snippet I'm working on: const functions={ top1: { f1: () => 'string', f2: (b: boolean, n: number) => 1 }, top2: { f3: (b: boolean) => b } } I am looking to define an apply f ...

Creating React components with TypeScript: Defining components such as Foo and Foo.Bar

I have a react component defined in TypeScript and I would like to export it as an object so that I can add a new component to it. interface IFooProps { title:string } interface IBarProps { content:string } const Foo:React.FC<IFooProps> = ({ ...

typescript mock extending interface

I'm currently working with a typescript interface called cRequest, which is being used as a type in a class method. This interface extends the express Request type. I need to figure out how to properly mock this for testing in either jest or typemoq. ...

After compiling the code, a mysterious TypeScript error pops up out of nowhere, despite no errors being

Currently, I am delving into the world of TypeScript and below you can find the code that I have been working on: const addNumbers = (a: number, b: number) => { return a + b } Before compiling the file using the command -> tsc index.ts, the ...

Why is TypeScript only supporting Promise<T> params and not Promise<T1,T2>?

I have been contemplating why the Promise<T> structure does not accept two parameters, such as Promise<T1,T2>. For instance: new Promise(function(resolve,reject){ ... err ? reject(err) : resolve(val); }); => ...