Angular HTML binding

后端 未结 21 2635
暖寄归人
暖寄归人 2020-11-21 04:00

I am writing an Angular application and I have an HTML response I want to display.

How do I do that? If I simply use the binding syntax {{myVal}} it en

21条回答
  •  粉色の甜心
    2020-11-21 04:49

    [innerHtml] is great option in most cases, but it fails with really large strings or when you need hard-coded styling in html.

    I would like to share other approach:

    All you need to do, is to create a div in your html file and give it some id:

    Then, in your Angular 2 component, create reference to this object (TypeScript here):

    import { Component, ViewChild, ElementRef } from '@angular/core';
    
    @Component({
        templateUrl: "some html file"
    })
    export class MainPageComponent {
    
        @ViewChild('dataContainer') dataContainer: ElementRef;
    
        loadData(data) {
            this.dataContainer.nativeElement.innerHTML = data;
        }
    }
    

    Then simply use loadData function to append some text to html element.

    It's just a way that you would do it using native javascript, but in Angular environment. I don't recommend it, because makes code more messy, but sometimes there is no other option.

    See also Angular 2 - innerHTML styling

提交回复
热议问题