Search code examples
htmlangulardata-binding

Angular data binding sending strings?


I'm new to angular, and I would like to know if there's is a way to send a string to the Html file with a variable inside?

test.ts

test: string = "Display this {{testText}}";
testText: string = "Success";

test.html

<p>{{test}}</p>

What I want to achieve is that it displays this: Display this Success.

I'm just curious if this is possible, perhaps I can retrieve from an API chunks of HTML string and display them like that.


Solution

  • **

    It is basic Javascript string operation. For this, there is nothing special with Angular at your TypeScript file.

    Without handling updates on test

    On Typescript file you have two options to merge strings:

    First Way:

    testText: string = "Success";
    test: string = `Display this ${this.testText}`;
    

    Second Way:

    testText: string = "Success";
    test: string = "Display this " + this.testText;
    

    Of course you can see a problem with both of them. What will happen when you update your test? Based on these ways, the testText just initializing when the component instance is created, so if you want to fetch changes on your test variable you should use the way from one of following **

    First Way:

    test.html

    <p>Display is {{testText}}</p>
    <p>{{'Display is ' + testText}}
    

    Socond Way:

    Specifically you can create a custom Pipe. You should check documentation about how are them work. For only this case you don't need to use this way. Pipes are generally for more generic or more complex operations.

    Third way:

    (more bad than others. Because change detector of Angular will not understand when your content should update the paragraph. You should use others.)
    

    test.ts

    getTestText() { return 'Display is ' + this.testText }
    

    test.html

    <p>{{ getTestText() }}</p>
    

    **

    Binding Dynamic Html Content

    For binding any dynamic HTML template you need to use innerHTML attribute like

    <div [innerHTML]="htmlVariable"></div>

    but this is not a trusted way because there is nothing to check is the html is trusted or is it valid etc. Or if the html contains the selector of any component, it won 't render as expected. You should use more complex ways to do it.