Angular 2 equivalent of ng-bind-html, $sce.trustAsHTML(), and $compile? - innerhtml

In Angular 1.x, we could insert HTML in real-time by using the HTML tag ng-bind-html, combined with the JavaScript call $sce.trustAsHTML(). This got us 80% of th way there, but wouldn't work when Angular tags were used, such as if you inserted HTML that used ng-repeat or custom directives.
To get that to work, we could use a custom directive that called $compile.
What is the equivalent for all of this in Angular 2? We can bind using [inner-html] but this only works for very simple HTML tags such as <b>. It doesn't transform custom angular 2 directives into functioning HTML elements. (Much like Angular 1.x without the $compile step.) What is the equivalent of $compile for Angular 2?

In Angular2 you should use DynamicComponentLoader to insert some "compiled content" on the page. So for example if you want to compile next html:
<div>
<p>Common HTML tag</p>
<angular2-component>Some angular2 component</angular2-component>
</div>
then you need to create component with this html as a template (let's call it CompiledComponent) and use DynamicComponentLoader to insert this component on the page.
#Component({
selector: 'compiled-component'
})
#View({
directives: [Angular2Component],
template: `
<div>
<p>Common HTML tag</p>
<angular2-component>Angular 2 component</angular2-component>
</div>
`
})
class CompiledComponent {
}
#Component({
selector: 'app'
})
#View({
template: `
<h2>Before container</h2>
<div #container></div>
<h2>After conainer</h2>
`
})
class App {
constructor(loader: DynamicComponentLoader, elementRef: ElementRef) {
loader.loadIntoLocation(CompiledComponent, elementRef, 'container');
}
}
Check out this plunker
UPD You can create component dynamically right before the loader.loadIntoLocation() call:
// ... annotations
class App {
constructor(loader: DynamicComponentLoader, elementRef: ElementRef) {
// template generation
const generatedTemplate = `<b>${Math.random()}</b>`;
#Component({ selector: 'compiled-component' })
#View({ template: generatedTemplate })
class CompiledComponent {};
loader.loadIntoLocation(CompiledComponent, elementRef, 'container');
}
}
I personally don't like it, it's look like a dirty hack to me. But here is the plunker
PS Beware that at this moment angular2 is under active development. So situation can be changed at any time.

DynamicComponentLoader is deprecated, you can use ComponentResolver instead
You could use this directive, add pipes if you need additional data manipulation. It also allows for lazy loading, you don't need it in your case, but it's worth mentioning.
Directive(I found this code and made some changes, you can do that too to make it fit your taste or use it as is):
import { Component, Directive, ComponentFactory, ComponentMetadata, ComponentResolver, Input, ReflectiveInjector, ViewContainerRef } from '#angular/core';
declare var $:any;
export function createComponentFactory(resolver: ComponentResolver, metadata: ComponentMetadata): Promise<ComponentFactory<any>> {
const cmpClass = class DynamicComponent {};
const decoratedCmp = Component(metadata)(cmpClass);
return resolver.resolveComponent(decoratedCmp);
}
#Directive({
selector: 'dynamic-html-outlet',
})
export class DynamicHTMLOutlet {
#Input() htmlPath: string;
#Input() cssPath: string;
constructor(private vcRef: ViewContainerRef, private resolver: ComponentResolver) {
}
ngOnChanges() {
if (!this.htmlPath) return;
$('dynamic-html') && $('dynamic-html').remove();
const metadata = new ComponentMetadata({
selector: 'dynamic-html',
templateUrl: this.htmlPath +'.html',
styleUrls: [this.cssPath]
});
createComponentFactory(this.resolver, metadata)
.then(factory => {
const injector = ReflectiveInjector.fromResolvedProviders([], this.vcRef.parentInjector);
this.vcRef.createComponent(factory, 0, injector, []);
});
}
}
Example how to use it:
import { Component, OnInit } from '#angular/core';
import { DynamicHTMLOutlet } from './../../directives/dynamic-html-outlet/dynamicHtmlOutlet.directive';
#Component({
selector: 'lib-home',
templateUrl: './app/content/home/home.component.html',
directives: [DynamicHTMLOutlet]
})
export class HomeComponent implements OnInit{
html: string;
css: string;
constructor() {}
ngOnInit(){
this.html = './app/content/home/home.someTemplate.html';
this.css = './app/content/home/home.component.css';
}
}
home.component.html:
<dynamic-html-outlet [htmlPath]="html" [cssPath]="css"></dynamic-html-outlet>

After reading a lot, and being close of opening a new topic I decided to answer here just to try to help to others. As I've seen there are several changes with the latest version of Angular 2. (Currently Beta9)
I'll try to share my code in order to avoid the same frustration I had...
First, in our index.html
As usual, we should have something like this:
<html>
****
<body>
<my-app>Loading...</my-app>
</body>
</html>
AppComponent (using innerHTML)
With this property you will be able to render the basic HTML, but you won't be able to do something similar to Angular 1.x as $compile through a scope:
import {Component} from 'angular2/core';
#Component({
selector: 'my-app',
template: `
<h1>Hello my Interpolated: {{title}}!</h1>
<h1 [textContent]="'Hello my Property bound: '+title+'!'"></h1>
<div [innerHTML]="htmlExample"></div>
`,
})
export class AppComponent {
public title = 'Angular 2 app';
public htmlExample = ' <div>' +
'<span [textContent]="\'Hello my Property bound: \'+title"></span>' +
'<span>Hello my Interpolated: {{title}}</span>' +
'</div>'
}
This will render the following:
Hello my Interpolated: Angular 2 app!
Hello my Property bound: Angular 2 app!
Hello my Interpolated: {{title}}
AppComponent Using DynamicComponentLoader
There is a little bug with the docs, documented in here. So if we have in mind that, my code should look now like this:
import {DynamicComponentLoader, Injector, Component, ElementRef, OnInit} from "angular2/core";
#Component({
selector: 'child-component',
template: `
<div>
<h2 [textContent]="'Hello my Property bound: '+title"></h2>
<h2>Hello my Interpolated: {{title}}</h2>
</div>
`
})
class ChildComponent {
title = 'ChildComponent title';
}
#Component({
selector: 'my-app',
template: `
<h1>Hello my Interpolated: {{title}}!</h1>
<h1 [textContent]="'Hello my Property bound: '+title+'!'"></h1>
<div #child></div>
<h1>End of parent: {{endTitle}}</h1>
`,
})
export class AppComponent implements OnInit{
public title = 'Angular 2 app';
public endTitle= 'Bye bye!';
constructor(private dynamicComponentLoader:DynamicComponentLoader, private elementRef: ElementRef) {
// dynamicComponentLoader.loadIntoLocation(ChildComponent, elementRef, 'child');
}
ngOnInit():any {
this.dynamicComponentLoader.loadIntoLocation(ChildComponent, this.elementRef, 'child');
}
}
This will render the following:
Hello my Interpolated: Angular 2 app!
Hello my Property bound: Angular 2 app!
Hello my Property bound: ChildComponent title
Hello my Interpolated: ChildComponent title
End of parent: Bye bye!

I think all you have to do is set the element you want to have compiled html with the [innerHTML]="yourcomponentscopevar"

Angular provided DynamicComponentLoader class for loading html dynamically. DynamicComponentLoader have methods for inserting components. loadIntoLocation is one of them for inserting component.
paper.component.ts
import {Component,DynamicComponentLoader,ElementRef,Inject,OnInit} from 'angular2/core';
import { BulletinComponent } from './bulletin.component';
#Component({
selector: 'paper',
templateUrl: 'app/views/paper.html'
}
})
export class PaperComponent {
constructor(private dynamicComponentLoader:DynamicComponentLoader, private elementRef: ElementRef) {
}
ngOnInit(){
this.dynamicComponentLoader.loadIntoLocation(BulletinComponent, this.elementRef,'child');
}
}
bulletin.component.ts
import {Component} from 'angular2/core';
#Component({
selector: 'bulletin',
templateUrl: 'app/views/bulletin.html'
}
})
export class BulletinComponent {}
paper.html
<div>
<div #child></div>
</div>
Few things you need to take care of :
Don't call loadIntoLocation inside the constructor of class . Component view is not yet created when component constructor is called. You will get error -
Error during instantiation of AppComponent!. There is no component
directive at element [object Object]
Put anchorName #child in html otherwise you will get error.
Could not find variable child

Have a look at this module https://www.npmjs.com/package/ngx-dynamic-template
After a long research, only this thing helped me. The rest of the solutions seems to be outdated.

Related

Ionic PDFJS Cannot match any routes. URL Segment: 'lib/ui/index.html'

I am trying to open a pdf in my ionic 5 application with the plugin
npm i # pdftron / pdfjs-express --save
but ionic shows me the error Cannot match any routes. URL Segment: 'lib / ui / index.html'
please how to correct this error?
my code:
app.component.html
<div class="page">
<div class="header">Angular sample</div>
<div #viewer class="viewer"></div>
</div>
app.component.ts
import { Component, ViewChild, OnInit, ElementRef, AfterViewInit } from '#angular/core';
import WebViewer from '#pdftron/pdfjs-express';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit, AfterViewInit {
#ViewChild('viewer', { static: false }) viewer: ElementRef;
wvInstance: any;
ngAfterViewInit(): void {
WebViewer({
path: '../lib',
initialDoc: '../files/webviewer-demo-annotated.pdf'
}, this.viewer.nativeElement).then(instance => {
this.wvInstance = instance;
})
}
ngOnInit() {
}
}
Have you used any of our angular samples here https://github.com/PDFTron?q=angular? You can clone one of the samples and take a look at how it is implemented

Vue 3 as a class component

currently in the project we uses Vue 2.x and our components works in such way
#Component({
template: `
<div>
some code ....
<div> `
})
export default class class1 extends Vue {
#Prop() data: IsomeData;
}
vue-class-component and vue-property-decorator allows us to right in this way, according the docs, #Component was replaced to #Options({}).
How can I migrate to Vue3 without headbreaking refactoring?
Try this.
<template>
<div>
some code ....
<div>
</template>
<script>
import { Vue } from "vue-class-component";
import { Prop } from "vue-property-decorator";
export default class Home extends Vue {
#Prop() data: IsomeData;
}
</script>

Angular template rendering non-encoded URL

How do I render a URL which is not encoded. Below is a sample
import { Component } from '#angular/core';
import { Router } from '#angular/router';
#Component({
selector: 'demo-app',
template: `<a [routerLink]="stringURL">Click here</a>`,
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
stringURL:string;
constructor(){
this.stringURL = "/url;mode=3"
}
}
The URL in the template has encoded string like /url%3Bmode%3D3 and I want it like /url;mode=3
How can I achieve this.
Here's the sample : https://stackblitz.com/edit/angular-q6mf3p
Thanks
You have to disable angular default URL encoding.
This post explains the solution quite well.
If the link is static, you can use the directive as follows: link to user component
If you use dynamic values to generate the link, you can pass an array of path segments, followed by the params for each segment.
For instance ['/url',{mode: 3}] means that we want to generate a link to /url;mode=3.
you code will work see this new link click to see
import { Component } from '#angular/core';
import { Router } from '#angular/router';
#Component({
selector: 'demo-app',
template: `<a [routerLink]="stringURL">Click here</a>`,
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
stringURL:any;
constructor(){
this.stringURL = ["/url",{mode:3}]
}
}

Angular2 access variables from another component

Tried EventEmitter but no chance and so little documentation... Any help appreciated
I have a component called sidebar and another one called header, when you click on a button from the header, it should hide the sidebar... How would you achieve this in angular2 ?
thanks
This is pretty easy with a Service you share between your Components.
For instance a SidebarService:
#Injectable()
export class SidebarService {
showSidebar: boolean = true;
toggleSidebar() {
this.showSidebar = !this.showSidebar;
}
}
In your sidebar component just put a *ngIf with the showSidebar variable from the SidebarService. Also don't forget to add the service in the constructor.
#Component({
selector: 'sidebar',
template: `
<div *ngIf="_sidebarService.showSidebar">This is the sidebar</div>
`,
directives: []
})
export class SidebarComponent {
constructor(private _sidebarService: SidebarService) {
}
}
In the component, where you want to handle the toggling of the sidebar also inject the SidebarService and add the click event with the service method.
#Component({
selector: 'my-app',
template: `
<div>
<button (click)="_sidebarService.toggleSidebar()">Toggle Sidebar</button>
<sidebar></sidebar>
</div>
`,
directives: [SidebarComponent]
})
export class App {
constructor(private _sidebarService: SidebarService) {
}
}
Don't forget to add the SidebarService to the providers in your bootstrap:
bootstrap(App, [SidebarService])
Plunker for example usage

How to define a template fom the `text/ng-template` source in angular2?

I am trying to apply the html from my internal text/ng-template script tag. but it's fails to work. how to apply html from the script tag?
Here is my code and html:
js part :
//our root app component
import {Component} from 'angular2/core'
#Component({
selector: 'my-app',
providers: [],
templateUrl: "template.html", //this is the id.
directives: []
})
export class App {
public title = "My Title";
private userName = "Test Name";
constructor() {
this.name = 'Angular2'
}
}
HTML part :
<body>
<my-app>loading...</my-app>
//template declared
<script type="text/ng-template" id="template.html">
<h2>{{title}}</h2>
<div>
<h2>Hello {{name}}</h2>
<h2>{{userName}}</h2>
</div>
</script>
</body>
I am getting a error :
Failed to load template.html
What is the correct way to use it?
Unfortunately, this is not, nor will be, supported in Angular 2 :\ https://github.com/angular/angular/issues/6126