I have a component with some feature and its html say a.component.ts
class AComponent {
....
}
a.component.html
<div>
Bunch of HTML with many logic
</div>
Now I have extended above a component in b.component.ts
class BComponent extends AComponent {
Have some it's own code
}
b.component.html
<div>
// Include A HTML
</div>
<div>
B's html code goes here
</div>
I don't want to use the A component directly here like <a-component></a-component> because in this case A Component code will be called twice.
Any Idea how to how only the html of a component in other component as part of the page without calling the component.
Related
In my Angular project (version 8) I am creating a list of static HTML from database and rendering it in parent HTML. Only the last div having innerHTML is rendered correctly, all the preceding divs having child html is not rendered correctly. The contents are jumbled. Basically the child html's style is not honored except for the last child html.
I am using sanitize html pipe for the div.
The angular component onInit queries DB in a loop. Each get call returns HTML text which is appended to an array of strings. The HTML text is basically PDF to HTML converted file. Each of the HTML file has its own style tag.
My guess is that only the last innerHTML's style is applied to all the preceding child innerHTML hence the jumbled contents (unless my guess is incorrect)
Any suggestion to solve the issue ?
HTML
<div *ngFor="let qBank of tsqm.selectedQuestions; let i = index">
<div class="page">
<div [innerHTML]="questionDataFromHtml[i] |
sanitizeHtml"></div>
</div>
</div>
Sanitize HTML:
#Pipe({ name: 'sanitizeHtml'})
export class SanitizeHtmlPipe implements PipeTransform {
constructor(private _sanitizer: DomSanitizer) { }
transform(value: string): SafeHtml {
return this._sanitizer.bypassSecurityTrustHtml(value);
}
}
Component:
ngOnInit(){
this.questionset = this.storage.get(quesId);
//pseudo code
forEach(item in this.questionset){
this.getHTMLfromDB(item)
}
}
getHTMLfromDB(question: QuestionBank) {
this.Service.getQuestionHtmlFile(question.questionFilePath).subscribe(res =>
{
this.questionDataFromHtml.push(res.text());
question.questionData.questionDataFromHtml = res.text();
});
Correct display. Question1 and Question2 are same
Correct display
Incorrect display. Question1 and Question2 are different
Incorrect display
Stackblitz:
stackblitz
The issue is all the css styling is overridden and the final values are applied.
Use id/class to apply the style to specific component.
I've made changes to your stackblitz example. Check here
In hello.component.ts
Applied red color to the text using text-red id.
export class HelloComponent {
#Input() name: string;
html1 =
"<html><head><style> #text-blue {color:blue;}</style></head><body><h2 id='text-blue'>Inner HTML1 in red</h2></body></html>";
html2 =
"<html><head><style> #text-red {color:red;}</style></head><body><h2 id='text-red'>Inner HTML2 in blue</h2></body></html>";
}
I solved this issue by using iFrame tag and srcdoc attribute. The backend service will return html text to angular. After DOM sanitizing the html documents are displayed in the iFrames.
I am using a v-bind:class binding on a component, with the goal of turning a css class on and off depending on the truthiness of a boolean in my Vue.js component.
When I in my template declare:
<aside v-bind:class="{'--opened':sidebarVisible}" class="sidebar" id="sidebar">
Script part of my component:
<script>
import { EventBus } from "#/event-bus.ts";
export default {
data(){
return {
sidebarVisible:false
}
}
//Cut for breavity
};
</script>
I expect Vue.js to modify the class to class="sidebar--opened" but instead I get class="sidebar --opened" (with an empty space between sidebar and --opened). How can I get around this behavior?
you have to give it full name of the class as this line will add a separate class to it. so the solution would be
<aside v-bind:class="{'sidebar--opened':sidebarVisible}" class="sidebar" id="sidebar">
Note: If it doesn't work then you might have to remove class 'sidebar' explicitly.
I am trying to add html content dynamically into a DIV. Statically this works nicely.
Code which works:
<popover-content #pop1
title="Cool Popover"
placement="right"
[closeOnClickOutside]="true">
Popped up!!!
</popover-content>
<div>
<span>Testing with <span [popover]="pop1" [popoverOnHover]="true">popover</span> as they are not working with DomSanitizer</span>
</div>
Now I need to generate this div content in the backend and then have to dynamically add this inside the div.
Code which doesn't work:
HTML:
<popover-content #pop1
title="Cool PopOver"
placement="right"
[closeOnClickOutside]="true">
Popped up!!!
</popover-content>
<div [innerHtml]="message | safeHtml">
</div>
.ts file:
this.message = '<span>Testing with <span [popover]="pop1" [popoverOnHover]="true">popover</span> as they are not working with DomSanitizer</span>'
Pipe:
import {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);
}
}
After this also the popover component was not getting called.
While inspecting, I did see that, for dynamically added innerHtml content to DIV, angular is not adding some special behavior to the tag attributes. Why so?
And how can I make it work?
With [innerHTML]="..." you can add HTML to the DOM, but Angular won't care what HTML it contains, except for sanitization.
Angular components, directives, event and property bindings only work for HTML added statically to a components template.
What you can do is to compile the HTML with a components template at runtime like explained in How can I use/create dynamic template to compile dynamic Component with Angular 2.0?
I am a newbie to the ReactJS world and trying to get into it. I am working on a style guide for which I need to display some HTML code as an example. I am using ReactPrism for that and I am not able to get the HTML output inside my PrismCode component, I have find a work around by using react-to-jsx which shows the JSX code instead of HTML.
This is the code:
import React from 'react';
import {PrismCode} from "react-prism";
import reactToJsx from 'react-to-jsx';
class CodePreview extends React.Component {
render (){
return (
<div>
{this.props.children}
<h5>Code example</h5>
<pre>
<PrismCode className="language-javascript">
{reactToJsx(this.props.children)}
</PrismCode>
</pre>
</div>
);
}
}
export default CodePreview;
So basically I want to render this.props.children (the component) as HTML code and not the content of it in the PrismCode
I even tried the following as shown on https://github.com/tomchentw/react-prism, but it doesn't work. Not sure what I am doing wrong!
<PrismCode className="language-javascript">
{require("raw-loader!./PrismCode")}
</PrismCode>
Have you considered writing your docs in markdown? I added some special tags for react:
```react:mirror
<Slider
value={7}
/>
```
This will show the rendered component and also the JSX syntax highlighted.
```react:demo
<PropsEditor>
<Slider
value={7}
/>
</PropsEditor>
```
This will render the component as well as a live editor to manipulate any props on the component.
```react
<SomeComponent />
```
Will just syntax highlight but not render the component.
At the top of my markdown file I can import any components I am using in the doc:
---
imports:
- import Slider from '../src/slider'
- import PropsEditor from 'props-editor'
---
The advantage of this way is that your docs work as normal markdown and it's easy to get the JSX as you have it as a string.
To get the HTML source I have a "View Source </> button which prints formatted html dynamically when clicked:
The steps are:
on click get the html of the react component
format the html using prism and a beautifier
insert it into the DOM
So wrap your react component and make a reference to the node:
<div ref={(n) => (this.fenceView = n)}>
And on click add the output below the component, relevant bits:
import prismjs from 'prismjs';
import beautify from 'xml-beautifier';
const RE_HTML_COMMENTS = /<!--[\s\S]*?-->/g;
removeCodeSource() {
const existingHtmlCode = this.fenceView.querySelector('.fence-generated-html');
if (existingHtmlCode) existingHtmlCode.remove();
}
renderCodeSource() {
const html = this.fenceView.children[0].innerHTML.replace(RE_HTML_COMMENTS, '');
const fenceCode = beautify(html, ' ');
const highlightedCode = prismjs.highlight(fenceCode, prismjs.languages.html);
this.removeCodeSource();
this.fenceView.insertAdjacentHTML('beforeend',
`<pre class="fence-generated-html language-html"><code>${highlightedCode}</code></pre>`);
}
in angular 2 I need to create a large html-template with redundant parts.
Therefore I want to create multiple html-templates and put them together by including them in the main html-file (like ng-include in angular1)
But how can I include sub-templates in the main-template?
example:
<!-- test.html -->
<div>
this is my Sub-Item
<!-- include sub1.html here-->
</div>
<div>
this is second Sub-Item
<!-- include sub2.html here-->
</div>
-
<!-- sub1.html -->
<div>
<button>I'am sub1</button>
</div>
-
<!-- sub2.html -->
<div>
<div>I'am sub2</div>
</div>
You can create components like sub1 sub2 etc. And On those child components add these html files as template .
On main html call the component selectors respectively. It will work
Let me tell you first of all that ng-include from Angular1.x is not supported by Angular2 so obviously $Compile is not present in Angular2. So, you can go ahead with CRF-ComponentFactoryResolver as shown here to add HTML dynamically with angular context.
DEMO--(CFR) : https://plnkr.co/edit/YdRlULhWQR3L3akAr2eb?p=preview
If your HTML piece has angular context, you should use CFR-ComponentFactoryResolver.
As in sub1.html, you have button, you might want to click it and fire its click event. This can be achieved with CFR as shown below,
You can do lot with CRF. This is probably the easiest example.
#Component({
selector: 'my-app',
template: `
<button (click)="addComponents()">Add HTML (dynamically using CRF)</button>
<h1>Angular2 AppComponent</h1>
<hr>
<div>
<h5>sub1.html goes here</h5>
<div class="container">
<template #subContainer1></template>
</div>
</div>
<hr>
<h5>sub2.html goes here</h5>
<div class="container">
<template #subContainer2></template>
</div>
`,
})
export class App {
name:string;
#ViewChild('subContainer1', {read: ViewContainerRef}) subContainer1: ViewContainerRef;
#ViewChild('subContainer2', {read: ViewContainerRef}) subContainer2: ViewContainerRef;
constructor(
private compFactoryResolver: ComponentFactoryResolver
) {
this.name = 'Angular2'
}
addComponents() {
let compFactory: ComponentFactory;
compFactory = this.compFactoryResolver.resolveComponentFactory(Part1Component);
this.subContainer1.createComponent(compFactory);
compFactory = this.compFactoryResolver.resolveComponentFactory(Part2Component);
this.subContainer2.createComponent(compFactory);
}
}
}