Angular 2 and Google Custom Search. Angular2 stripping html tag
Asked Answered
T

1

7

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);
}
Thousandth answered 29/7, 2016 at 11:15 Comment(0)
T
7

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);
}
Thousandth answered 29/7, 2016 at 14:2 Comment(3)
Just wanted to mention that now DomSanitizationService is replaced wth DomSanitizer in angular 2 cliWieche
I am trying this but I don't see nothing I am using the Ionic 3 and TSAnimosity
this works, but any idea on how can we prefill search text on load ?Plumbum

© 2022 - 2024 — McMap. All rights reserved.