How can Angular 7 incorporate inline JavaScript scripts in a component?

I am facing an issue while trying to integrate the places.js library into my Angular 7 project. I have added the necessary script in my 'index.html' file as follows:

 <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="eb9b878a888e98c58198abdac5daddc5df">[email protected]</a>"></script>
  <script>
    var placesAutocomplete = places({
      appId: 'myAppId',
      apiKey: 'myApiKey',
      container: document.querySelector('#addressInput')
    });
  </script>

However, it only works when I have the following input field in my 'index.html':

<input type="search" id="address-input" placeholder="Where are we going?" />

I tried moving this input field to a component but encountered an error:

<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="087864696b6d7b26627b483926393e263c">[email protected]</a>:1 Uncaught Error: Algolia Places: 'container' must point to an <input> element.

Is there a way to make this script work with a component? The documentation does not mention anything about TypeScript. I also attempted to use npm install and import * from 'places.js', but the problem persists. Any help would be greatly appreciated.

Answer №1

It's recommended to utilize this within an Angular Component:

import { Component, OnInit } from "@angular/core";
import places from "places.js";

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent implements OnInit {
  title = "my-app";

  ngOnInit(): void {
    const placesAutocomplete = places({
      appId: "appId",
      apiKey: "appKey",
      container: document.querySelector("#address-input")
    });
  }
}

Make sure to also include the following code snippet in your polyfill.js for proper functionality:

(window as any).process = {
  env: { DEBUG: undefined }
};

(window as any).global = window;

Answer №2

Despite my best efforts, I was unsuccessful when attempting it your way.

To resolve this issue, please ensure that you download the places.js file and place it in the script folder.

Next, update the angular.json file within the builder > scripts section as shown below:

 "build": {
      "builder": "@angular-devkit/build-angular:browser",
      "options": {
        ...
        "assets": [...],
        "styles": [...],
        "scripts": [
          "script/places.js"
        ]
      },

Answer №3

To ensure proper organization, make sure to place all your Place code within a component and initialize it in the ngOnInit() lifecycle hook.

import { Component, OnInit } from '@angular/core';
import * as Places from 'places';

@Component({
  selector: 'my-app',
  templateUrl: './yourComponent.html'
})
export class AppComponent implements OnInit  {

  ngOnInit(){
    Places({
      appId: 'myAppId',
      apiKey: 'myApiKey',
      container: document.querySelector('#addressInput')
    });
  }
}

In your yourComponent.html:

<input type="search" id="address-input" placeholder="Where are we going?" />

Answer №4

Based on my observations, the input needs to be loaded before it is called and attached to your index. If you try to attach it before the input loads, it will not work as expected.

var placesAutocomplete = places({
  appId: 'myAppId',
  apiKey: 'myApiKey',
  container: document.querySelector('#addressInput')
});

There are a few different approaches you could take, but personally, I would create a service for this purpose, similar to the following:

declare var places:any;
@Injectable({providedIn:'root'})
export class PlacesServices {
      setup(){
        var placesAutocomplete = places({
        appId: 'myAppId',
        apiKey: 'myApiKey',
        container: document.querySelector('#addressInput')
       });
      }

}

Then, inject this service into your component and only call it when the input with the correct ID is fully loaded. Utilize ngAfterViewInit to ensure that the views are loaded correctly.

ngAfterViewInit(){
   this.placesService.setup();
  //Call the setup function here in the component containing the input
}

The JavaScript script can be either added directly to index.html or implemented as described in Hien's answer.

This response was written quickly, so there may be some typos. However, the main concept should still be clear. Hopefully, this solution works for you!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Swapping XML tag names in Node.js

I'm trying to use nodejs to rename all tags in an XML file. My initial thought was to utilize regex and the fs module to read the file, but I quickly felt overwhelmed. <RESULTS> <ROW> <COLUMN NAME="DATA_CRIACAO"><![CD ...

Find the difference in weeks between two dates using MongoDB aggregate

My current dilemma involves extracting student data for each week within an academic year based on a start date and end date. To achieve this, I have devised an array that contains the start and end dates for every week. The process involves iterating thro ...

Experiencing difficulties integrating react-moveable with NEXTjs: Error encountered - Unable to access property 'userAgent' as it is undefined

I've been grappling with this problem for the past few hours. I have successfully implemented react-moveable in a simple node.js app, but when I attempt to integrate it into a NEXTjs app, an error crops up: TypeError: Cannot read property 'userAg ...

Capturing a still image from a video stream with opentok

Can someone explain what is the main container for the image element in the provided code snippet? I couldn't find any clear explanation on the tutorial website, so insight on how this specific section of code operates would be greatly appreciated. v ...

Calling an API twice in Angular Universal SSR - once from the frontend and the other from the backend

I am currently working on implementing SSR using Angular Universal, but I am encountering two issues: I am noticing two hits on my server in the server logs, one from the frontend and the other from the backend. When the universal server calls the AP ...

In React, the state of the "interval" component remains constant

Currently, I am implementing React 16.10 with TypeScript and encountered an issue with my code: const [state, setState] = useState<State>({ test: 1 }); //Upon mounting the component, we initiate our interval useEffect(() =&g ...

Guide to using get() and res.sendFile() function to redirect webpages

Why is the page not redirecting properly? In my index.html file, I have this script: $.get( "/loginPage", function( data ) {}); The purpose of this script is to check if a user is logged in. If they are, it should redirect them to the lobbyPage. This is ...

Each page in NextJS has a nearly identical JavaScript bundle size

After using NextJS for a considerable amount of time, I finally decided to take a closer look at the build folder and the console output when the build process is successful. To my surprise, I noticed something peculiar during one of these inspections. In ...

When attempting to open a native app using JavaScript, it fails to function properly. However, the same code successfully opens the

These questions revolve around a web application developed in React that will be accessed through smartphones' browsers. I conduct testing on an iPhone using both Safari and Chrome. One of the steps involves opening a native authentication app. As pe ...

Launching Node.js + Express on the server

Trying to Deploy Node.js + Express on Server I'm diving into Node.js and Express development for the first time, and before I fully commit to using these technologies in a new project at work, I want to test them on our server to ensure everything ru ...

When utilizing the catch function callback in Angular 2 with RxJs, the binding to 'this' can trigger the HTTP request to loop repeatedly

I have developed a method to handle errors resulting from http requests. Here is an example of how it functions: public handleError(err: any, caught: Observable<any>): Observable<any> { //irrelevant code omitted this.logger.debug(err);//e ...

Testing the window object using Jest

I have created a function that simulates a hostname. This function is defined before the actual test, prior to the describe block. const mockHost = (hostname: string) => { global.window = Object.create(window); Object.defineProperty(window, ' ...

Changing buffer from base64 to UTF-8 encoding in Node.js

My application imports messages from the Notes folder of Gmail using the imap npm module. When following the example on their GitHub page, all message contents are read into a buffer: stream.on('data', function(chunk) { count += chunk.len ...

Showing text on an ajax loader

While making an ajax call, I have implemented functions that are called on success. To enhance user experience, I am displaying a spinner during the call and hiding it once completed. My goal is to show a message along with the spinner to indicate which fu ...

incapable of destructuring two objects simultaneously

Is there a way to map movies using columns as a property reference? For example: {movies.map(item => {columns.map(column => item.column.path)})} When I try this, the result is always undefined. The 'movies' array contains detailed inform ...

Glistening: sending reactiveValues to conditionalPanel

Is it possible to pass a reactiveValues to the condition of a conditionalPanel? If so, what is the correct method? Below is my attempt in the UI.R file for the conditionalPanel: conditionalPanel(condition = "values.cond == 0", etc. I have defined values ...

Steps for calling a function in index.js using Node.js

I am just starting to learn about NodeJS and I have a question that might seem basic to some, but I would really appreciate some assistance here. Here is the content of my index.js file:- 'use-strict'; const { myauth } = require('./src/au ...

The jQuery ajax function seems to be malfunctioning when attempting to send a post request

Having trouble with AJAX? Let me show you my approach to making a POST request to my RESTful service using AJAX: var lat = marker.getPosition().lat(); var lng = marker.getPosition().lng(); //xmlhttp.open("GET","http://192.168.1.100:8080/MapDemo/serv ...

Unable to successfully inject a template into the parent state using ui-view

No matter what I try, this stubborn thing refuses to function properly. The stateTwo in the provided plunker simply won't integrate into the controller of the parent state. What on earth could I be doing incorrectly?? http://plnkr.co/edit/N9wpkwJ8ByL ...

What could be causing the data in getServerSideProps to be altered?

After fetching data from an API and passing it to index.js using getServerSideProps, I noticed that the prop array is initially in order by rank [1, 2, 3, etc]. Here's an example of the data: [ {rank: 1, price: 123}, {rank: 2, price: 1958}, {rank: ...