4

How can I bind input texts to span innerHTML in Angular6?

ts file

...
finance_fullname: string;
...

template file

<input type="text" id="finance_fullname" [(ngModel)]="finance_fullname">
<span class="fullname" ngBind="finance_fullname"></span>

3 Answers 3

12

I can say most secure way would be innerText or textContent.

<span class="fullname" [textContent]="finance_fullname"></span>
<span class="fullname" [innerText]="finance_fullname"></span>

Even AngularJS were using textContent for one way binding. It only extract the model value and dump directly inside the specified html node. Even though if you pass html it will add that html as a text(decoded html) on the page.

Demo

innerHTML would also work for you, but it could be dangerous, as it will give a chance to inject malicious content on the page in form of html.

Sign up to request clarification or add additional context in comments.

1 Comment

For more in-depth explanations for different html node element text properties: stackoverflow.com/questions/24427621/… Note that it is not recommended to use innerHTML unless you specifically intend to insert HTML and make the precautions to avoid an XSS attack
4

I don't know why you are reading from angularjs since you are working with angular 6. If you want double binding just do it like this.

<input type="text" id="finance_fullname" [(ngModel)]="finance_fullname">
<span class="fullname">{{finance_fullname}}</span>

2 Comments

It's a form? Because If you have many inputs you just put in your ts form:any = {} and then in your html [(ngModel)]="form.finance_fullname" and it should work
I figured out this one, this wasn't working because I declared the variable "finance_fullname" in ts file, once I removed all the declared variables this also working fine. Thanks in advance.
4

You can do it in two ways

(i) You can use [innerHTML]

<input type="text" id="finance_fullname" [(ngModel)]="finance_fullname">
<span class="fullname" [innerHTML]="finance_fullname"></span>

STACKBLITZ DEMO

(ii) Just bind using the two way data binding

STACKBLITZ DEMO

<input type="text" id="finance_fullname" [(ngModel)]="finance_fullname">
<span class="fullname">{{finance_fullname}}</span>

4 Comments

[innerHTML] working as I expected, but the second one is not working, what is the reason?
check the demo above
I checked the demo, it seems you didn't declare the variable in ts file but I declared, that is the reason? The demo is working perfect but not for me.
yeah that would matter, in that case you use ngModelchange and reassign the value

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.