I have scoured the possible answers and none of them work. All the innerHTML and PRE tag examples are fine with code or text, but NOT with HTML. Here is EXACTLY what I want to put into a variable:
<div [ngStyle]="{'display':'flex', 'flex-direction':'column', 'width': '100vw', 'height': '100vh'}">
<top-header>
<a class="topHeaderItem" (click)="goToHome()">Home</a>
<a class="topHeaderItem" (click)="gotoTOC()">Contents</a>
</top-header>
AND THAT is precisely what I want to show up on the screen - every single character because it is a tutorial example.
Here's my agony. My HTML:
1
<div [innerHTML]="code1">
</div>
<hr>
2
<div>
<pre>
<code [innerHTML]="code1"></code>
</pre>
</div>
<hr>
3
<div [innerHTML]=code1>
</div>
My component.ts:
import {Component} from '#angular/core';
#Component({
selector: 'cs-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.scss']
})
export class HomeComponent {
code1 = `
<div [ngStyle]="{'display':'flex', 'flex-direction':'column', 'width': '100vw', 'height': '100vh'}">
<top-header>
<a class="topHeaderItem" (click)="goToHome()">Home</a>
<a class="topHeaderItem" (click)="gotoTOC()">Contents</a>
</top-header>
`
constructor() {
}
}
And now my pathetic output:
Binding with [innerHTML] will interpret the HTML. If you want to show the HTML code, you could use [innerText] instead, or simply use string interpolation as #Vega noted. That will properly escape the HTML.
<div>{{ code1 }}</div>
// or
<div [innerText]="code1"></div>
Binding to [innerText] will preserve the line breaks.
The innerHTML is if you want to actually show HTML that is inserted in the DOM as part of the document.
You want the normal {{ code1 }} syntax which will encode the variable for displaying.
Adding a code and a pre will style it the way you want (or you can do the same through CSS by setting the css of the container to have white-space:pre)
<div><code><pre>{{code1}}</pre></code></div>
example at https://plnkr.co/edit/cVnQZeWnqJCYTBmndmB6?p=preview
Related
Trying to HTML code to view the resulting HTML using the innerHTML property, but as you can see in the example below, it doesn't. The HTML code is viewed as the HTML tags and only, instead of creating the elements it renders them as simple text.
https://codepen.io/Dralius/pen/OJzoZxm
#Component({
selector: 'my-app',
template: `
<span [innerHTML]='working'> </span>
<span [innerHTML]='notWorking'> </span>
`
})
class AppComponent {
working="<h1>hello world angular 6</h1>";
notWorking='<p> Random Text </p>'
constructor() {
// TODO: Define your Angular component implementation
}
}
an idea can be to parse the notWorking string into valid html with domparser (for sample) before inject it in innerHTML
https://codepen.io/jeremy-denis/pen/rNpZKzO?editors=1111
const { Component, VERSION } = ng.core;
#Component({
selector: 'my-app',
template: `
<span [innerHTML]='working'> </span>
<span [innerHTML]='notWorking'> </span>
`
})
class AppComponent {
working="<h1>hello world angular 6</h1>";
notWorking='<p> Random Text </p>'
constructor() {
this.notWorking = new DOMParser().parseFromString(this.notWorking, 'text/html').body.innerText;
}
}
This won't work just because of one little problem : It just won't. You are not using HTML tags, only the "symbols" of them. What is your problem exactly here? using < is mostly used for printing out the literal symbol on the page, not as HTML tag.
I have a string, in a variable "prod.de.description", that is a description of an object, like that:
"<p><strong>Test</strong></p><p><strong><span style="background-color: #ed7e32;">Test2</span></strong></p>"
When I use innerhtml, it's show only the strong but not the background color. Here is the html code and the result:
<div class="col-10" style="padding-left:0; font-size:0.9rem">
<div class="row">
<div class="col-3 text-right">
<label class="modal-tag">DESCRIPTION</label>
</div>
<div class="col-9">
<p [innerHTML]="prod.de.description"></p>
</div>
</div>
That's what I get since now:
Why I don't get the background color under Test2 but only the strong?
I'm newbie of HTML. Thanks a lot!
You are using same quotation marks (") inside and outside of string.
That might cause the problem. Use different ones. Maybe something like this:
"<p><strong>Test</strong></p><p><strong><span style='background-color: #ed7e32;'>Test2</span></strong></p>"
you are using innerHTML directive of framework and it sanitises the content before putting into your dom. It will remove styles tag and script things as security issue. Outsiders can attack with their on content. To prevent that, framework does this thing.
However, framework also gives way to escape this when you know that you are putting content from trusted sources.
Follow this link:
https://stackblitz.com/edit/angular-8-app-example-mzdwkd
import { Component } from '#angular/core';
import { DomSanitizer } from '#angular/platform-browser';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ],
})
export class AppComponent {
description = '<p><strong>Test</strong></p><p><span style="background-color: #ed7e32;">Test2</span></p>';
constructor(private sanitizer: DomSanitizer){}
transformYourHtml(htmlTextWithStyle) {
return this.sanitizer.bypassSecurityTrustHtml(htmlTextWithStyle);
}
}
HTML:
<p [innerHTML]="transformYourHtml(description)"></p>
I am using #HostBinding('class') to inject classes into the host element. The classes to be injected are generated based on user-supplied parameters. The problem I ran into and I could not find anyone else experiencing is that the classes are applied in an order different from the way I expected them.
For example, having a component defined below:
import {Component, HostBinding, Input} from '#angular/core';
#Component({
selector: '[icon]',
template: `
<ng-content></ng-content>
`
})
export class SuiIconComponent {
#Input() iconType = '';
#HostBinding('class')
get classes(): string {
return [this.iconType, 'icon'].join((' '));
}
}
When I apply the component like shown below:
<div icon iconType="car"></div>
And inspect, I see <div class="icon car"></div> instead of the appropriately formatted <div class="car icon"></div>.
I have tried reversing the array before joining but that did not help either.
Is there any way I get the classes to get rendered in the proper order?
Edit: I realized the classes are being rearranged in alphabetic order.
I'm not sure why angular changes the order, but you can solve your problem with little bit of change in your template.
#Component({
selector: 'icon',
template: `
<div [ngClass]="iconType + ' icon'">
<ng-content></ng-content>
</div>
`
})
export class SuiIconComponent {
#Input() iconType = '';
}
and use it as follows
<icon iconType="car">
Some content here
</icon>
This question already has answers here:
Angular HTML binding
(24 answers)
Closed 3 years ago.
I want to know if there is any way to use the HTML tag name (<p> for e.g.) which is obtained from a variable?
The following is the code I tried:
app.component.ts
import { Component,OnInit } from '#angular/core';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
name = 'Angular';
somevalues = [1, 2, 3, 4, 5]
tagName;
getFromCharCode(index) {
return String.fromCharCode('A'.charCodeAt(0) + index);
}
ngOnInit(){
this.tagName = "p";
}
}
app.component.html
<div *ngFor="let x of somevalues; let i = index">
{{x}} - {{i}}
{{ getFromCharCode(i) }}
<h1>{{tagName}}
</h1>
</div>
If I tried like:
<{{tagName}}></{{tagName}}>
I'm getting error like
Template parse errors:
Unexpected closing tag "{{tagName}}". It may happen when the tag has already been closed by another tag.
I referred to this, but I find it is pretty complex for a simple replacement. Is there any other way to achieve this?
EDIT-1:
Many of you suggest to use innerHTML but that would be feasible incase of small contents. In my typical case, I would like to have all my html content in the same file and I would get only the name of the tag in ts file
You can use innerHTML for this:
ngOnInit(){
this.tagName = "<p></p>";
}
<div [innerHTML]="tagName"></div>
Hi first of all this way will not work as the interpolation considers the value as a string so it will always appear as a text on the screen.
By your question what i understand is you want to add HTML inside an already existing element.
The easiest way way would be: -
in your ts give your variable the value that you want to insert so eg.
tagName = `<div> Some text inside </div>`;
and then in your html you can simply do:-
<h1 [innerHTML]="tagName">
other way to do this would be to get the reference of the element in ts and insert it from there
Try this one
<div *ngFor="let x of somevalues; let i = index">
{{x}} - {{i}}
{{ getFromCharCode(i) }}
<h1 innerHtml="<{{tagName}}></{{tagName}}>"></h1>
</div>
I want to dynamically place an html code in my html code, So I write the following code:
<ng-container [innerHTML]="buttonIcon"></ng-container>
Angular says innerHTML is not valid attribute for ng-container
I don't want to use third html tag like follows:
<div [innerHTML]="buttonIcon"></div>
So how can I insert html codes without any tag inner html binding?
[outerHTML]
will do the trick to replace the outer element.
In your case
<div [outerHTML]="buttonIcon"></div>
It's true, that it's important to have a clean HTML structure for e.g. keeping CSS rules as simple as possible.
You can use ngTemplate:
<ng-template #buttonIcon>
<div> Your html</div>
</ng-template>
<ng-container
*ngTemplateOutlet="buttonIcon">
</ng-container>
** Please read the comments. This answer might be wrong. I dont know, have not looked into it again **
ng-container does not get rendered to html, it is a mere structural directive.
The Angular is a grouping element that doesn't interfere with styles or layout because Angular doesn't put it in the DOM.
So there is no element to put html into. You need to work with a sub-div. If there is no need for a sub-div in your opinion, then you could most probably also just replace ng-container with div itself and not use the container at all.
If for any reason you need to replace the DOM element you can use a div with an id and then use the #ViewChild decorator and ElementRef to get access to the nativeElement from the controller and set the outerHtml property.
app.component.tml
<div #iconButton></div>
app.component.ts
import { Component, ViewChild, ElementRef, ViewEncapsulation, AfterViewInit }from '#angular/core';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ],
encapsulation: ViewEncapsulation.None
})
export class AppComponent implements AfterViewInit{
#ViewChild('iconButton')
iconButton: ElementRef;
ngAfterViewInit(){
this.iconButton.nativeElement.outerHTML = '<button>My button</button>'
}
}
We need to use none as encapsulation policy because our template only includes the div to be replaced.
Stackblitz example: https://stackblitz.com/edit/angular-fa1zwp