How to Translate HTML String to Real HTML Element by Ng-For in Angular 2

How to translate HTML string to real HTML element by ng-for in Angular 2?

In angular2 there's no ng-include, trustAsHtml, ng-bind-html nor similar, so your best option is to bind to innerHtml. Obviously this let you open to all kind of attacks, so it's up to you to parse/escape the content and for that you can use pipes.

@Pipe({name: 'escapeHtml', pure: false})
class EscapeHtmlPipe implements PipeTransform {
transform(value: any, args: any[] = []) {
// Escape 'value' and return it
}
}

@Component({
selector: 'hello',
template: `<div [innerHTML]="myHtmlString | escapeHtml"></div>`,
pipes : [EscapeHtmlPipe]
})
export class Hello {
constructor() {
this.myHtmlString = "<b>This is some bold text</b>";
}
}

Here's a plnkr with a naive html escaping/parsing.

I hope it helps :)

TypeScript - Append HTML to container element in Angular 2

1.

<div class="one" [innerHtml]="htmlToAdd"></div>
this.htmlToAdd = '<div class="two">two</div>';

See also In RC.1 some styles can't be added using binding syntax


  1. Alternatively
<div class="one" #one></div>
@ViewChild('one') d1:ElementRef;

ngAfterViewInit() {
d1.nativeElement.insertAdjacentHTML('beforeend', '<div class="two">two</div>');
}

or to prevent direct DOM access:

constructor(private renderer:Renderer) {}

@ViewChild('one') d1:ElementRef;

ngAfterViewInit() {
this.renderer.invokeElementMethod(this.d1.nativeElement', 'insertAdjacentHTML' ['beforeend', '<div class="two">two</div>']);
}

    3.
constructor(private elementRef:ElementRef) {}

ngAfterViewInit() {
var d1 = this.elementRef.nativeElement.querySelector('.one');
d1.insertAdjacentHTML('beforeend', '<div class="two">two</div>');
}

Angular Translate HTML tags

Angular sanitizes any html strings during its interpolation.
In order to get around this you will need to mark the HTML as safe in $sce before injecting. Then also use ngBindHtml to output the html.

I've not used angular-translate before, but this may work:

//app is the main module
app.filter("htmlSafe", ['$sce', function($sce) {
return function(htmlCode){
return $sce.trustAsHtml(htmlCode);
};
}]);

//then to output it
<span data-ng-bind-html="'page.PAGES_WELCOME' | translate | htmlSafe"></span>

How can I convert strings of HTML into HTML in my template (Angular2/TypeScript)?

You can bind to innerHtml like:

<div [innerHtml]="someProp.htmlText"></div>

Angular does not instantiate any components where the selectors that match tags or attributes in HTML added this way nor will it resolve any bindings (like {{xx}})

See also How to bind raw html in Angular2

Insert HTML into view from AngularJS controller

For Angular 1.x, use ng-bind-html in the HTML:

<div ng-bind-html="thisCanBeusedInsideNgBindHtml"></div>

At this point you would get a attempting to use an unsafe value in a safe context error so you need to either use ngSanitize or $sce to resolve that.

$sce

Use $sce.trustAsHtml() in the controller to convert the html string.

 $scope.thisCanBeusedInsideNgBindHtml = $sce.trustAsHtml(someHtmlVar);

ngSanitize

There are 2 steps:

  1. include the angular-sanitize.min.js resource, i.e.:

    <script src="lib/angular/angular-sanitize.min.js"></script>
  2. In a js file (controller or usually app.js), include ngSanitize, i.e.:

    angular.module('myApp', ['myApp.filters', 'myApp.services', 
    'myApp.directives', 'ngSanitize'])

ngx-translate: use with interfaces, *ngFor and switch

Well, I browsed through the ngx-translate docs. I can't find any hint according to the approach you describe here. And I have to add that I used ngx-translate for several years in different projects.

The aim of translators is always to have one single identifier string by which you then go into the JSON-file of the currently activated language and search for the matching translation.

In your example you have

en.json

{
"name": "name",
"age": "age"
}

es.json

{
"name": "nombre",
"age": "edad"
}

And then the UI will show either the english or the spanish string-representation of this identifier.

There is no way around.

To make it more obvious you could use more specific identifiers like this, for example

en.json

{
"global.name": "name",
"global.age": "age",
"xyz.component.direction": "direction",
"abc.component.working-hours": "working hours"
}

es.json

   "global.name": "nombre",
"global.age": "edad",
"xyz.component.direction": "dirección",
"abc.component.working-hours": "horas laborales"

Angular Template - Dynamically generated HTML is output as a string and not HTML

The problem you are facing is a very common one considering that in a lot of scenarios, we intend to somehow inject our own HTML into the template, and it can be easily done via innerHTML attribute like you have demonstrated. Also, as you have correctly mentioned, this injected HTML is just plain HTML and wont support Angular magic since It's injected after the Angular Code Compilation.

So what's the solution? The one that you propose simply fails because it is string interpolation (with double curly braces) and renders on the document whatever you mention. Dom Sanitizer won't help since that too is injecting HTML after compilation so no angular magic.

One sensible solution I can think of is to create an angular component for you table header, provide it inputs that you are using to construct custom HTML and then pass all the input to Table Header Component (Via @Input()) and let it use it's template HTML depending on conditions arrived upon from inputs.

@Component({
selector: 'my-th',
template: '<th [title]="Inp1" [ngClass]="{'some-class':true}"></th>',
})
export class TableHeadComponent {
@Input() inp1;
@Output() outpt;
class: string = 'xyz';
}

And the parent component could then use it like

<my-th [inp1]="inp" (outpt)="handle()"></my-th>


Related Topics



Leave a reply



Submit