Angular HTML binding

后端 未结 21 2613
暖寄归人
暖寄归人 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:40

    You can apply multiple pipe for style, link and HTML as following in .html

    <div [innerHTML]="announcementContent | safeUrl| safeHtml">
                        </div>
    

    and in .ts pipe for 'URL' sanitizer

    import { Component, Pipe, PipeTransform } from '@angular/core';
    import { DomSanitizer } from '@angular/platform-browser';
    
    @Pipe({ name: 'safeUrl' })
    export class SafeUrlPipe implements PipeTransform {
        constructor(private sanitizer: DomSanitizer) {}
        transform(url) {
            return this.sanitizer.bypassSecurityTrustResourceUrl(url);
        }
    }
    

    pipe for 'HTML' sanitizer

    import { Component, Pipe, PipeTransform } from '@angular/core';
    import { DomSanitizer } from '@angular/platform-browser';
    
    @Pipe({
        name: 'safeHtml'
    })
    export class SafeHtmlPipe implements PipeTransform {
        constructor(private sanitized: DomSanitizer) {}
        transform(value) {
            return this.sanitized.bypassSecurityTrustHtml(value);
        }
    }
    

    this will apply both without disturbing any style and link click event

    0 讨论(0)
  • 2020-11-21 04:43

     <div [innerHTML]="HtmlPrint"></div><br>

    The innerHtml is a property of HTML-Elements, which allows you to set it’s html-content programatically. There is also a innerText property which defines the content as plain text.

    The [attributeName]="value" box bracket , surrounding the attribute defines an Angular input-binding. That means, that the value of the property (in your case innerHtml) is bound to the given expression, when the expression-result changes, the property value changes too.

    So basically [innerHtml] allows you to bind and dynamically change the html-conent of the given HTML-Element.

    0 讨论(0)
  • 2020-11-21 04:43

    The way to dynamically add elements to DOM, as explained on Angular 2 doc, is by using ViewContainerRef class from @Angular/core.

    What you have to do is to declare a directive that will implement ViewContainerRef and act like a placeholder on your DOM.

    Directive

    import { Directive, ViewContainerRef } from '@angular/core';
    
    @Directive({
      selector: '[appInject]'
    })
    export class InjectDirective {
    
      constructor(public viewContainerRef: ViewContainerRef) { }
    
    }
    

    Then, in the template where you want to inject the component:

    HTML

    <div class="where_you_want_to_inject">    
      <ng-template appInject></ng-template>
    </div>
    

    Then, from the injected component code, you will inject the component containing the HTML you want:

    import { Component, OnInit, ViewChild, ComponentFactoryResolver } from '@angular/core';
    import { InjectDirective } from '../inject.directive';
    import { InjectedComponent } from '../injected/injected.component';
    
    @Component({
      selector: 'app-parent',
      templateUrl: './parent.component.html',
      styleUrls: ['./parent.component.css']
    })
    export class ParentComponent implements OnInit {
    
      @ViewChild(InjectDirective) injectComp: InjectDirective;
    
      constructor(private _componentFactoryResolver: ComponentFactoryResolver) {
      }
    
      ngOnInit() {
      }
    
      public addComp() {
        const componentFactory = this._componentFactoryResolver.resolveComponentFactory(InjectedComponent);
        const viewContainerRef = this.injectComp.viewContainerRef;
        const componentRef = viewContainerRef.createComponent(componentFactory);
      }
    
      public removeComp() {
        const componentFactory = this._componentFactoryResolver.resolveComponentFactory(InjectedComponent);
        const viewContainerRef = this.injectComp.viewContainerRef;
        const componentRef = viewContainerRef.remove();
      }
    
    }
    

    I added a fully working demo app on Angular 2 dynamically add component to DOM demo

    0 讨论(0)
  • 2020-11-21 04:44

    I apologize if I am missing the point here, but I would like to recommend a different approach:

    I think it's better to return raw data from your server side application and bind it to a template on the client side. This makes for more nimble requests since you're only returning json from your server.

    To me it doesn't seem like it makes sense to use Angular if all you're doing is fetching html from the server and injecting it "as is" into the DOM.

    I know Angular 1.x has an html binding, but I have not seen a counterpart in Angular 2.0 yet. They might add it later though. Anyway, I would still consider a data api for your Angular 2.0 app.

    I have a few samples here with some simple data binding if you are interested: http://www.syntaxsuccess.com/viewarticle/angular-2.0-examples

    0 讨论(0)
  • 2020-11-21 04:44

    Just to make for a complete answer, if your html content is in a component variable, you could also use:

    <div [innerHTML]=componementVariableThatHasTheHtml></div>
    
    0 讨论(0)
  • 2020-11-21 04:45

    In Angular 2 you can do 3 types of bindings:

    • [property]="expression" -> Any html property can link to an
      expression. In this case, if expression changes property will update, but this doesn't work the other way.
    • (event)="expression" -> When event activates execute expression.
    • [(ngModel)]="property" -> Binds the property from js (or ts) to html. Any update on this property will be noticeable everywhere.

    An expression can be a value, an attribute or a method. For example: '4', 'controller.var', 'getValue()'

    Example here

    0 讨论(0)
提交回复
热议问题