Is it best way to data binding with [innerHTML], angular 4 - html

My problem is that in angular 4 there are few ways to data bind with HTML to TS like {{myText}}, [], () and other than those we can use [innerHTML]="myText"
what is the best way to bind simple variable to HTML among {{}}, [innerHTML] ?

Try like this :
<div [innerHTML]="htmlString"></div>
in typescript file :
htmlString: string = "Hello world"; <!-- if want to display string -->
htmlString: string = "<h1>Hello world</h1>"; <!-- if want to display html element -->

Bind it with {{yourText}} is it is not containing any HTML markups
Bind it with [innerHTML] = "youtText" if it has any HTML markups

Related

Bind external HTML component file to json data from calling page in Angular

with Angular 14, I'm using an ag grid to display rows of data in my main component page. I select a row, click a button and I want to call an auxiliary component HTML file in a separate directory that contains its own typescript file. I am able to collect the row data as JSON data but I want to insert the auxiliary component HTML into my main page.
Q: How can I bind the auxiliary html component to appear in my main html?
Directory Structure
ClientApp
src
app
MyObject
MyObject-grid-main
MyObject-grid-main.css
MyObject-grid-main.html
MyObject-grid-main.ts
MyObject-grid-auxiliary
MyObject-grid-auxiliary.css
MyObject-grid-auxiliary.html
MyObject-grid-auxiliary.ts
MyObject-grid-main.html
<button (click)="getSelectedRowData()">Get More Info</button>
<ag-grid-angular #agGrid id="ag-grid"></ag-grid/angular>
...
<div>
<!-- Here I want to insert MyObject-grid-auxiliary.html after I bind the JSON data -->
</div>
MyObject-grid-main.ts
#ViewChild('agGrid' grid!: GridApi;
getSelectedRowData()
{
const selectedData = this.grid.getSelectedRows();
const jsonDataString = JSON.stringify(selectedData);
alert(`Selected Data:\n${jsonDataString}`); // display in popup
// Here is where I want to bind the JSON data to the MyObject-grid-auxiliary.html
// and have it appear in the place holder above
}
MyObject-grid-auxiliary.html
<h2 class="title">{{data.title}}</h2>
...
<span>{{data.remarks}}</span>
...
<tr *ngFor="let pos of data.locations">
<td>
<span>{{pos.position.lat}}</span>
</td>
<td>
<span>{{pos.position.long}}</span>
</td>
<td>
<span>{{pos.lastReportedOnDateTime}}</span>
</td>
</tr>
you can simply pass a MyObject-grid-main.ts class property set at first to null as MyObject-grid-auxiliary input and then check in the auxiliary component with an ngIf when the data are set, then show your stuff.
in getSelectedRowData set the class property and content should will be display in the auxiliar component
Update with example:
in your MyObject-grid-main.ts add a new property called
auxiliarData = null;
in MyObject-grid-main.html add the auxiliary component where you need.
<myobject-grid-auxiliary [data]="auxiliarData"></myobject-grid-auxiliary>
in the function getSelectedRowData add the update logic, example
const selectedData = this.grid.getSelectedRows();
const jsonDataString = JSON.stringify(selectedData);
alert(`Selected Data:\n${jsonDataString}`);
...
this.auxiliarData = selectedData;
in MyObjectGridAuxiliary.ts
export class MyObjectGridAuxiliary {
#Input() data = '';
}
in MyObject-grid-auxiliary.html
<div *ngIf="data"> put your html here ... </div>
so, whenever the MyObjectGridAuxiliary.data is defined the component will show you html with your data.

display variable html image

In Angular 2 code, I have defined the image as:
public rObj:any = {};
this.rObj.imgsrc ="http:/../.png";
Want to render this from my HTML:
<img src = {{rObj.imgsrc}}>
There is no display.Any help appreciated.Thanks!
Use one way binding on the src attribute. Any html attribute can be bound to.
... so for you this is what you are looking for.
<img [src]="rObj.imgsrc" />
Another example..
<a [href]="myHref"></a>
You are using the wrong data binding:
string binding: <elt attr="Hello World"/>
input (component → template): <elt [attr]="x"/>
event listener (template → component): <button (click)="someFunction"/>
two-way data binding: <elt [(attr)]="x"/> (not used a lot, use forms instead)
So you actually need here to write <img [src]="rObj.imgsrc"/>

The result is incorrect html element is get json in ionic 2

I used get json in ionic.
$http.get($scope.webServiceUrl+"example.php")
.then(function(response){
$rootScope.lists = response.data;
});
I wrote the webservice with php
echo json_encode($data,JSON_HEX_TAG);
return json data and print page
text: "<h1>enes</h1>"
Json [{"id":"0","text":"<h1>enes</h1>"}]
jsonviewer Image
Result when I print to the page
enter image description here
Does not accept is html element. How can i solve?
I think you have to use ng-bind-html directive if you are sure it's safe and can be rendered as unencoded HTML.
<div ng-controller="ExampleController">
<p ng-bind-html="myHTML"></p>
</div>

ng-bind-html not working with my $scope.variable

I am trying to add something like dynamic HTML using ng-bind-html but its not working with $scope variable
Here is my Angular code
1)My controller
$scope.name = "Parshuram"
$scope.thisCanBeusedInsideNgBindHtml = $sce.trustAsHtml("<div>{{name}}</div>");
Also that my string is dynamic
"<div><table class=" + "\"table table - bordered table - responsive table - hover add - lineheight table_scroll\"" + "><thead><tr><td>Name</td><td>Age</td></tr></thead><tbody><tr ng-repeat=" + "\"tr in dyna\"" + "><td>{{tr.name}}</td><td>{{tr.age}}</td></tr></tbody></table></div>"
So i cant replace every variable with $scope
2)- My HTML
<div ng-app="mymodule" ng-controller="myModuleController">
<div ng-bind-html="thisCanBeusedInsideNgBindHtml"></div>
</div>
I got this output
{{name}}
My expected output is
Parshuram
Please can anyone help i am stuck at this point,does that $sce does not bind scope variable?? ..
I've created a working plnkr here: https://plnkr.co/edit/uOdbHjv1B7fr0Ra1kXI3?p=preview
the problem is that ng-bind-html is not bound to the scope.
you should manually compile the content.
a valid and reusable solution should be creating a directive, whitout using any external modules.
function compileTemplate($compile, $parse){
return {
link: function(scope, element, attr){
var parsed = $parse(attr.ngBindHtml);
function getStringValue() { return (parsed(scope) || '').toString(); }
scope.$watch(getStringValue, function() {
$compile(element, null, -9999)(scope);
});
}
}
}
<div ng-app="mymodule" ng-controller="myModuleController">
<div ng-bind-html="thisCanBeusedInsideNgBindHtml" compile-template></div>
</div>
ng-bind-html does what it says on the tin: it binds html. It doesn't bind angular template code into your dom.
You need to do this instead:
$scope.thisCanBeusedInsideNgBindHtml =
$sce.trustAsHtml("<div>"+$sanitize(name)+"</div>");
To do this you'll want to include the module ngSanitize from the javascript angular-sanitize.js. See https://docs.angularjs.org/api/ngSanitize
If you want to insert some html that includes angular directives then you should write your own custom directive to do it.
In your html just use
{{name}}
The {{var}} notation is to be used in the HTML code to evaluate that variable.
You can do :
$scope.thisCanBeusedInsideNgBindHtml = $sce.trustAsHtml('<div ng-bind="name"></div>');
Sorry I make another answer.
If you have
$scope.thisCanBeusedInsideNgBindHtml = $sce.trustAsHtml("<div>{{name}}</div>");
Then you can do
var str = "<div>{{name}}</div>";
var output = str.replace('{{name}}', $scope.name);
It seems to be the only option.

How to render a HTML tag from json value using angularJs

// json is like this
"_unparsedString": "<p>test<\/p>"
// HTML
<div>Preamble : '{{item2._unparsedString}}'</div>
//Output
Preamble : <p>test<\/p>
but how to render that tag and display it using angular ?
//Output should be like this
Preamble : test
Instead of passing string to view directly, you should use sce.trustAsHtml to pre-process the html.
$scope.bindHTML = $sce.trustAsHtml(item2._unparsedString);
Then in your view template, use ng-bind-html to handle html binding.
<div>Preamble : <div ng-bind-html="bindHTML"></div></div>
As you mentioned you have an array of object, it's not that easy to cast them in your controller, you can bind $sce to your $scope then call trustAsHtml in your view
So in your controller
myapp.controller('mainController', function ($scope, $http, $filter, $sce) {
$scope.$sce = $sce;
...
}
Then in your html view
<div>Preamble {{$index+1}} : <span ng-bind-html="$sce.trustAsHtml(item1.Preamble._unparsedString)"></span></div>
Please check this working example: http://jsfiddle.net/Shital_D/b9qtj56p/6/
Download file - angular-sanitize.js and include it in your app.
var app = angular.module('myApp', ["ngSanitize"]);
app.controller('myController', function($scope,$compile) {
$scope.html = '<p>Your html code</p>';
});
<div ng-app="myApp">
<div ng-controller="myController">
<p ng-bind-html="html"></p>
</div>