Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 and Google Custom Search. Angular2 stripping html tag

I'm trying to add Google Custom Search into my angular 2 application. Using the code from the custom search works when I put it into a jsfiddle, but I'm having issues getting it to work when inserted into my component.

The issue seems to be, that by the time the code to insert the script runs, the html tag <gcse:search> is stripped of it's gcse: part to become <search> and I guess the script that runs then can't find any elements to work on.

My.component.html is essentially:

<gcse:search></gcse:search>

and in My.component.html.ts I have a function which implements ngOnInit

ngOnInit(){
    var cx = '016820916711928902111:qw0kgpuhihm';
    var gcse = document.createElement('script');
    gcse.type = 'text/javascript';
    gcse.async = true;
    gcse.src = 'https://cse.google.com/cse.js?cx=' + cx;
    var s = document.getElementsByTagName('script')[0];
    s.parentNode.insertBefore(gcse, s);
}
like image 802
James Avatar asked Jul 29 '16 11:07

James


1 Answers

This is not a nice solution but I got it working by passing in the <gcse:search> tag to the InnerHTML of a container div using bypassSecurityTrustHtml of the DomSanitizationService, rather than having it already existing.

my.component.html now looks like:

<div class="google-media-search" [innerHTML]="gcsesearch"></div>

and my.component.ts has the following included:

import {DomSanitizationService, SafeHtml} from '@angular/platform-browser';

...

constructor(
    private sanitizer: DomSanitizationService,
    ...
){}

gcsesearch: SafeHtml;

ngOnInit() {
    this.gcsesearch = this.sanitizer.bypassSecurityTrustHtml("<gcse:search></gcse:search>");

    var cx = '016820916711928902111:qw0kgpuhihm';
    var gcse = document.createElement('script');
    gcse.type = 'text/javascript';
    gcse.async = true;
    gcse.src = 'https://cse.google.com/cse.js?cx=' + cx;
    var s = document.getElementsByTagName('script')[0];
    s.parentNode.insertBefore(gcse, s);
}
like image 199
James Avatar answered Nov 02 '22 07:11

James