Angular2 Tag <innerHtml] Angular2 not working

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

@Component({ selector: 'app-root', template: '<app-a [my-html]="my-html"> </app-a>', styleUrls: ['./app.component.css'] }) export class AppComponent { my-html= '<span> {{variableFromAComponent}}</span>'; } @Component({ selector: 'app-a', template: '<div [innerHtml]="my-html"> </div>', }) export class AComponent { @Input('my-html') my-html:any; public variableFromAComponent='its work!'; } 

I want to see the result: his work! (from variableFromAComponent) But I see that {{variableFromAComponent}} (angular2 tags do not work).

+2
source share
4 answers

I found a solution in angular2-dynamic-component

 <template dynamic-component [componentContext]="self" [componentModules]="dynamicExtraModules" [componentTemplate]='"here html tags with angular2 tags"'> </template> 
+2
source

Angular does not process HTML added by [innerHTML]="..." at all. It is simply added as is and what it is. You may even need to use the Sanitizer, so for security reasons nothing is shy (see RC.1, some styles cannot be added using the binding syntax ).

If you want to add components dynamically, you can use ViewContainerRef.createComponent() , for example, as described in Angular 2 dynamic tabs using user-selected components

0
source

There are several ways you can do this.

COMPONENT INTERACTION

If there is a relationship between components between parents and children, you can use Input() and Output() to pass values ​​between them

This child component gets the value through 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 switch from child to parent.

SERVICES

Another way is to create a service that is introduced into both components. One component can send a value to a service, and another can receive that value. In Angular2, this is often achieved using observable data for the object.

0
source

You can use the 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>' ); } 
-1
source

Source: https://habr.com/ru/post/1259423/


All Articles