Angular2 [innerHtml] angular2 tag doesn't work

前端 未结 4 884
忘掉有多难
忘掉有多难 2021-01-15 13:49

I want to inject html in my a-component with angular2 tags from another component.

@Component({
  selector: \'app-root\',
  template: \'

        
相关标签:
4条回答
  • 2021-01-15 14:30

    There are a couple ways that you can do this.

    COMPONENT INTERACTION

    If there is a parent/child relationship between the components then you can use Input() and Output() to pass values between them

    This child component gets the value through the Input()

    child.component.ts

    import { Component, Input } from '@angular/core';
    @Component({
      selector: 'child',
      template: '<div>{{myHtml}}</div>', // these curly braces add the text as innerHTML
      providers: [ FoodsService]
    })
    export class ChildComponent implements OnInit {
       @Input() myHtml: string;
    }
    

    which is passed from the parent through the template:

    parent.component.html

    <child [myHtml]="'You're String Here (or a variable set to "its work")'"></child>
    

    You can use Output() to go from child to parent.

    SERVICES

    The other way is to create a service that gets injected into both components. One component can send a value to the service and the other can get that value. In Angular2 this is often achieved by using observables to a data object.

    0 讨论(0)
  • 2021-01-15 14:40

    I found a solution in angular2-dynamic-component

    <template dynamic-component
              [componentContext]="self"
              [componentModules]="dynamicExtraModules"
              [componentTemplate]='"here html tags with angular2 tags"'>
    </template>
    
    0 讨论(0)
  • 2021-01-15 14:45

    You can use Renderer2 Class for this.

    import { ElementRef, Renderer2 } from '@angular/core';
    
    constructor (
      private elementRef: ElementRef,
      private renderer: Renderer
    ) {}
    
    public ngAfertViewInit(): void {
      this.renderer
         .setElementProperty(
            this.elementRef.nativeElement, 
            'innerHTML',
            '<h1> Nice Title </h1>'
         );
    }
    
    0 讨论(0)
  • 2021-01-15 14:51

    Angular doesn't process HTML added by [innerHTML]="..." at all. It is just added as is and that's it. You might even need to use the Sanitizer, so nothing gets stripped for security reasons (see In RC.1 some styles can't be added using binding syntax).

    If you want to dynamically add components, you can use ViewContainerRef.createComponent() for example like explained in Angular 2 dynamic tabs with user-click chosen components

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