Angular directives inside InnerHTML - javascript

I know its not possible to inject angular directive along html code inside inner html, is there any work around it? I'm trying to read the html and the directive from a html file and inject it inside a div, I thought about using component factory and create the component dynamically but the directive in the html file can be anywhere in the code not sure how I can append it to the right place in dom, I don't have much experience working with component factory so please let me know if there is a way.
ngOnInit(): void {
let loading = this.loadingService.addTask();
this.route.paramMap
.take(1)
.subscribe(params => {
let page: string = params.get("page") || "";
if (page) {
this.trainingService.getPageContent(page)
.take(1)
.subscribe(res => {
this.content = res;
this.loadingService.completeTask(loading);
})
}
else {
this.loadingService.completeTask(loading);
}
},
error => {
this.notificationService.error("Error retrieving training page", error);
this.loadingService.clearAllTasks();
})
here is my template
<div [innerHtml]="content"></div>
here is an html page example that should be injected (this is an external html page file)
<div class="row">
<div class="col-md-12">
<div class="panel panel-default b">
<div class="panel-body">
<div class="row">
<!--the directive-->
<sa-azure-media-player [source]="the link"></ss-azure-media-player>
</div>
</div>
</div>
</div>
</div>

There isn't a way to do this. The workaround would be to change the way you inject html. Instead of injecting as html, write a sub-component, give it the right info (as an [json-]object!), and off you go.
In case you do not have control of the incoming info (in your case html), you are forced to mould it into an object, so you can use it in angular.
In a recent project I had to have text content that might contain iframes (iframes don't work well in angular). The solution was to parse and save the content in the backend as a JSON-object containing text- and iframe-parts in the right order (that cost some time, unfortunately). Once I got hold of it in Angular, I could inject the texts and iframes of the JSON-object by using typescript. And, of course, do the right thing for the right element.
So, in case you have control over the incoming info (be it html or whatever kind of identifiable object), that's where you should change the procedure (and make full use of the angular MVC-stuff). In case you do not have control over that, please provide some more details as to what needs to be done and what the cicumstances are.

Related

angular ngFor call javascript

I having HTML code like this
<div class="owl-carousel owl-theme owl-loaded">
<div class="owl-stage-outer">
<div class="owl-stage" *ngFor="let product of products; let i=index;">
<div class="owl-item">
<carouselFixture [stream]="product.stream" *ngIf="product.viewModelType == 'ProductSummary'" ></carouselFixture>
</div>
</div>
</div>
This is working fine. The problem I face is when the new product is added immediately it has to be shown in the owl carousel... actually it is loading but wrongly as shown in the image below
So to solve the problem we need to call the below add function in ngFor
$('#add').on('click', function () {
var html = '<div class=\"item\"><carouselFixture
[stream]="product.stream" *ngIf="product.viewModelType ==
'ProductSummary'" ></carouselFixture></div>';
console.log(html);
owl.trigger('add.owl.carousel', [html, 0])
.trigger('refresh.owl.carousel');
});
Can anyone tell me how to call this 'add' function...
AngularDart doesn't allow for dynamic components to be added to the page using pure html like that. This is for security, and performance reasons. It doesn't actually put the full angular engine in the page at runtime.
It does have other ways of doing this tho. The easiest is to add another entry onto the list and it will be displayed in the for loop.
The other possibility is to use the ComponentFactory to add it to the page https://webdev.dartlang.org/api/angular/angular/ComponentFactory-class
I'm not sure what owl is doing exactly in its call, but you could add the html without the angular component and use the component factory to insert it in the right place after owl does it's thing.

Using text-nodes to render JSON data into ready HTML page

I'm trying to achieve something similar to what JSRender does, but I'm not sure how to go about it. Consider the HTML "template" below:
<!DOCTYPE html>
<body>
<div class="content">
<div class="notifications">{{:notifications}} notifications</div>
<div class="something else">this is {{:something_else}} to show</div>
</div>
</body>
</html>
Supposed I have JSON data like so:
{"notifications": "3", "something_else": "some arbitrary data"}
How do I populated this data into the HTML page? The way JSRender does it seems to involve creating a separate template in a <script> tag, then populating the data into the template and finally copying the template into an empty container. Is there a way to avoid this template redefinition? I believe my HTML page can already act like a template as demonstrated above.
The Question: is it possible to display JSON data into a ready HTML page (such as above) with defined "data positions"? As part of the challenge, using $('.notifications').html()-related methods should be avoided since this would be cumbersome when handling large extensive data.
You can do that using top-level JsViews top-level data-linking - with an element such as a <span> for each insertion point.
<div class="content">
<div >this is <span data-link="something_else></span> to show</div>
...
Code:
$.link(true, ".content", data);
In addition, the data is data-bound to the HTML.
Here is a sample which shows the data-binding by letting you actually change a data property dynamically:
It also shows data-linking to the src and title attributes of an <img> tag. See here for more information about different data-link targets.
var data = {notifications: "3", something_else: "some arbitrary data",
imgData: {img1: {src: "http://www.jsviews.com//icons/android-chrome-36x36.png",
desc: "some image"}}};
$.link(true, ".content", data, {replace: true});
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jsviews/0.9.90/jsviews.js"></script>
<div class="content">
<div ><span data-link="notifications"></span> notifications</div>
<div >this is <span data-link="something_else"></span> to show</div>
<img data-link="src{:imgData.img1.src} title{:imgData.img1.desc}"/>
<br/>Edit: <input data-link="something_else"/>
</div>
While BorisMoore's answer addresses the question adequately, I crafted a "hack" that also appears to work with the ability to support attributes on almost all elements, though I don't know to what extent it is reliable.
However, this requires one to change the data structure to also indicate the type of element and even the part of it (attribute) where the data is to be inserted. The data would need to look like so:
{"notifications": "span:|3", "something_else": "span:|some arbitrary data", "avatar":"img.alt:|A"}
Then in JQuery, one could do something like so:
$.each(data, function(key, value) {
value = value.split(":|");
var element = value[0];
value = value[1];
if(element.indexOf('.') == -1){
var content = $(element + ':contains("{{:'+key+'}}")').last().html().replace("{{:"+key+"}}", value);
$(element + ':contains("{{:'+key+'}}")').html(content);
}else{
element = element.split('.');
var attribute = element[1];
element = element[0];
$(element + '['+attribute+'="{{:'+key+'}}"]').last().attr(attribute, value);
}
});
EDIT: The main drawback of this method is that it unbinds all attached events when an elements property is modifed this way.

Angular: How to implement ng-include like functionality in Angular 5?

Is there any functionality to render html file dynamically inside a components template based on the path? I have the path to local html file now I need to display the content of it inside a components template. In Anular 1.x we had ng-include, any similar functionality in Angular5?
<div class="row blogdetail-container">
{{blogSelected.description}} // currently interpolates the path
</div>
variable blogSelected.description contains the path to html file and I want to replace its content here.
Okay so the only reasonably straight-forward way I can think of to do this is to use an http request to get the contents of the html file then use that in the [innerHtml] attribute.
private dynamicTemplate: any = "";
http.get(blogSelected.description).map((html:any) => this.dynamicTemplate = sanitizer.sanitize(html));
then use
<div class="row blogdetail-container" [innerHtml]="dynamicTemplate"></div>
NOTE 1: remember to include http as a dependency for this component.
NOTE 2: remember to include sanitizer as a dependency for this component
NOTE 3: remember to validate blogSelected.description before calling the http request to check it's actually a valid URL.

Override a components template in Angular2/4?

If I detail the problem I'm trying to solve, it will help with my question.
I want to use HTML in the Angular Material tooltip, the current template doesn't enable this functionality:
<div class="mat-tooltip"
[ngClass]="tooltipClass"
[style.transform-origin]="_transformOrigin"
[#state]="_visibility"
(#state.done)="_afterVisibilityAnimation($event)">
{{message}}
</div>
In order to use HTML in the tooltip I'd like to override the template to the following:
<div class="mat-tooltip"
[ngClass]="tooltipClass"
[innerHTML]="message"
[style.transform-origin]="_transformOrigin"
[#state]="_visibility"
(#state.done)="_afterVisibilityAnimation($event)">
</div>
Is this possible? Is there another method I'm overlooking to achieve what I'm looking for?
The html file cannot be changed, however you can access the element from the component.ts file
#ViewChild('dataContainer') dataContainer: ElementRef;
loadData(data) {
this.dataContainer.nativeElement.innerHTML = data;
}
as found in thie SO-answer.

How to create a messaging service across application in Angular JS?

I want to show messages to the end user, just like Google, at the top center of the web panel.
I don't want to include the HTML and related script everywhere in every form and list and chart that I have. I want to centralize this messaging functionality into a service (in Angular JS term) that can be used everywhere.
And just like Google, I want to be able to show rich text in my messages, that is, I want to include links and probably other HTML stuff there. For example instead of showing Customer is defined, I want to show Customer is defined, <a href='#/customer/addPhone'>Now add a phone</a> to guide the user.
What I've done is to place the messages HTML in the root layout of my single paged application:
<div class="appMessages">
<span ng-show="message" ng-click="clearMessage()" ng-bind-html="message"></span>
</div>
and in our controllers, we inject the $rootScope and try to set the message property on it.
Yet I get no results. Can you guide me please?
As a general best practice I would avoid using $rootScope to pass the messages but rather use a dedicated service to update the message,
On your case the problem might be that you need to use angular $sce service to mark your html as trusted.
or load ng-santizemodule instead (which is a seperate module you need to load see offical doc)
That is needed because angular security requires you to explicitly check the html, if the source of your messages are from your code only, and not users inupts you can use the trustAsHtml as you know for sure it a safe html.
On your controller inject $sce, and bind it to your scope, and then use the $sce.trustAsHtml(value) function.
<div class="appMessages">
<span ng-show="message" ng-click="clearMessage()" ng-bind-html="$sce.trustAsHtml(message)"></span>
</div>
angular.module('app', [])
.component('message', {
controller: function($sce, messagService){
this.messagService = messagService;
this.$sce = $sce;
},
template: '{{$ctrl.message}}<div ng-bind-html="$ctrl.$sce.trustAsHtml($ctrl.messagService.message)"></div>'
})
.service('messagService', function(){
this.message = '';
this.updateMessage = function(message){
this.message = message;
}
})
.controller('mainCtrl', function($scope, messagService){
$scope.updateMessage = function () {
messagService.updateMessage('wow <b style="color:yellow;">shiny</b> message');
};
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<div ng-controller="mainCtrl" ng-app="app">
<message></message>
<button type="button" ng-click="updateMessage()"> update message</button>
</div>

Categories