简体   繁体   中英

Angular 4 parsing html with ngmodel

I am having some an issue with parsing a string in my view which has br tags that is bound using ngModel for example,

Here is my string

this.customer_address = this.customer.customer_name + '<br>' +
        this.customer.address.street + '<br>' + this.customer.address.postcode + '<br>' + this.customer.address.country;

and here is what I have in my HTML,

 <md-input-container class="example-full-width">
        <textarea [readonly]="invoice.lock || invoice.lock_archive" mdInput placeholder="Billing Address" name="address" [(ngModel)]="customer_address">

        </textarea>
      </md-input-container>

This seems to print the br tags within the textarea however I would like to escape them but I would also like to keep them when I am saving the object for example, when a new line is added I a br tag is added. I am not sure what best options.

In case you want to add the <br> to the text area value (so it will be visible to the user) you can just add the text to the inside of the textarea element:

<md-input-container class="example-full-width">
    <textarea [readonly]="invoice.lock || invoice.lock_archive" mdInputplaceholder="Billing Address" name="address" [(ngModel)]="customer_address">
        {{customer_address}}
    </textarea>
  </md-input-container>

In this case, the <br> tags will be visible so the user will see the following value inside the textarea:

John Doe <br> 123 Broadway <br> 12345 NY <br> USA

In case you want your text to be beautiful to the user, you can add this to the property innerHTML of the element. So you could do the following:

<md-input-container class="example-full-width">
    <textarea [readonly]="invoice.lock || invoice.lock_archive" mdInputplaceholder="Billing Address" name="address" [(ngModel)]="customer_address" [innerHTML]="customer_address">

    </textarea>
  </md-input-container>

In this case the address is compiled as HTML and will look as follows:

John Doe
123 Broadway
12345 NY
USA

You can also add the brackets to the visual of a page by using the 'ampersand element' like follows:

&lt; = <
&gt; = >

I think this is a better way and I think it is actually a best practice. I Hope this answers your question

The solution to my problem was to use a simple CSS property of white-space: pre-line; which preserves the white spaces on the text area. So my data is saved as some text \\n\\n line break so in my bank-end I do a simple replace of \\n with <br/>

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