Obtaining a function from the Lit Element CDN bundle file within a TypeScript file

I have successfully created a compact lit element bundle file using rollup.config.js. This bundle file has been uploaded to Netstorage, and here is how my lit element is structured:

import {customElement} from "lit/decorators.js";
import {LitElement} from "lit";

@customElement('my-lit-element')
export class MyLitElement extends LitElement {

  constructor() {
    super();
    console.log('this is test log');
  }

  /**
   * invoked when a component is added to the document's DOM
   */
  connectedCallback() {
    super.connectedCallback();
  }

    testMethod() {
      console.log('Hi from testMethod()');
    }

}

declare global {
  interface HTMLElementTagNameMap {
    'my-lit-element': MyLitElement;
  }
}

This is the content of my rollup.config.json:

import merge from 'deepmerge';
import { createSpaConfig } from '@open-wc/building-rollup';
import json from "@rollup/plugin-json"

// import copy from 'rollup-plugin-copy'
import pkg from './package.json'
 
const baseConfig = createSpaConfig({
  developmentMode: process.env.ROLLUP_WATCH === 'true',
  injectServiceWorker: false
});
 
export default merge(baseConfig, {
  // any <script type="module"> inside will be bundled by rollup
  input: './index.html',
  plugins: [
    // ... other rollup plugins
    json()
  ]
});

I would like to access the testMethod() function within a typescript file in Angular. I tried accessing the function in an html file which worked as shown below:


<script type="module" src="https:path_to_my-lit-element-cdn_bundleFile.js"></script>
 <my-lit-element></my-lit-element>

<script>
  const el = document.querySelector('my-lit-element');
  const ob = customElements.whenDefined('my-lit-element').then(() => {

    //works
    el.testMethod()

    }
  });

However, I am looking to achieve the same functionality in a typescript file.

I attempted to access it directly like this:

In index.html:

And in the typescript file, I tried to access the testMethod() in a similar manner:

const el = document.querySelector('my-lit-element');
  const ob = customElements.whenDefined('my-lit-element').then(() => {

    //works
    el.testMethod()

    }
  });

Unfortunately, it does not work. Whenever I try to use el.testMethod(), it starts displaying an error message:

Property 'testMethod' does not exist on type 'Element'.

If anyone knows how to call methods within a cdn JavaScript file from a typescript file, your help would be greatly appreciated.

Answer №1

It seems to be a typescript issue. You can utilize the global interface HTMLElementTagNameMap to specify customElement types.

Create an interface to link all the public methods and properties of web components.

export interface MyLitComponent extends HTMLElement {
       testMethod():void;
      //Define all the web component properties
}

     

Include HTMLElementTagNameMap in the global interface so that you can treat the web component selector in TypeScript just like a regular HTML element

declare global {
          interface HTMLElementTagNameMap {
            'my-lit-element': MyLitComponent;
          }
}

Now, the querySelector return type would become MyLitComponent

const el = document.querySelector('my-lit-element'); //MyLitComponent
  const ob = customElements.whenDefined('my-lit-element').then(() => {
    el.testMethod()
  }
});

Example

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

Easily identify the user's language and redirect them on the client side using JavaScript with Akamai

My website is available in 18 different languages, each with its own translated domain. There are unique products only available in specific languages, making it crucial for users to easily switch between languages. However, the language selector may not b ...

Step-by-step guide to start an AngularJs application using TypeScript

I have developed an AngularJS App using TypeScript The main app where I initialize the App: module MainApp { export class App { public static Module : ng.IModule = angular.module("mainApp", []) } } And my controller: module MainApp { exp ...

Formatting code in Visual Studio 2017 for TypeScript files

When attempting to format my TypeScript Code using Ctrl+K+D, nothing seems to happen. Strangely, it works fine with all other code files. What could I be doing incorrectly? ...

At compile time, Typescript runs smoothly, but errors may arise during runtime

Currently, I am delving into learning Typescript and have encountered a snag in my code. Despite searching extensively for a solution, I have been unable to find any relevant material pertaining to my issue. Below is the code snippet in question: <code ...

connecting and linking template content with an Observable

I have a CRUD page that needs to be updated after every operation. I have implemented Observable and the CRUD functions (specifically Add and Delete) are working fine, but I need to manually refresh the page to see the changes reflected. After trying to ...

Challenges when transitioning to TypeScript within a React project

I'm in the process of converting my React app Components to Typescript. After installing the TS package and setting up a tsconfig.json file and react-app-env.d.ts files, I made sure to change the file extensions from .js to .tsx. However, I encounter ...

Ways to specify an unused parameter within a function

As I work on my code, I encounter the need to separate the key and value from a request params object in order to validate the value using ObjectID. To achieve this, I decided to iterate over an array of entries and destructure the key and value for testin ...

Turn off page animation for a specific page in Ionic 4

While I know that disabling page transitions in the app.module.ts file using IonicModule.forRoot({animated: false}) will turn off transitions and animations for the entire app, I am looking for a way to only disable the page transition for a particular p ...

Storing user information in local storage with the Capacitor Storage Plugin: A Comprehensive Guide

I'm attempting to integrate Firebase Authentication into my Angular application. Here's the signUp() function within my AuthService: signUp(email: string, password: string, name: string) { const userCredential = from( firebase.auth(). ...

Tips for presenting a quiz in a random order and preventing duplicate questions in a React Native app

Hello everyone, I am working on creating a Quiz app in React Native that displays questions randomly without any duplication. So far, I have managed to display the Quiz questions randomly, but I'm stuck on preventing duplicates. This is a new learning ...

Steps for reinstalling TypeScript

I had installed TypeScript through npm a while back Initially, it was working fine but turned out to be outdated Trying to upgrade it with npm ended up breaking everything. Is there any way to do a fresh installation? Here are the steps I took: Philip Sm ...

What exactly do .d.ts files encompass?

Currently, I am utilizing react-table within a Typescript Next.js project. This particular package is made up of modules (such as sorting, pagination, etc.) that are not automatically included but need to be enabled in the primary useTable hook. The defaul ...

Service Activation Button Click Event

When coding, I designated the path as follows: { path:'home', component: homeComponent; } In app.component.html: <button (click)="routerLink='/home'" An error occurred here Are you trying to navigate to the home page by ...

What is the best way to implement the useCallback hook in Svelte?

When utilizing the useCallback hook in React, my code block appears like this. However, I am now looking to use the same function in Svelte but want to incorporate it within a useCallback hook. Are there any alternatives for achieving this in Svelte? con ...

The phenomenon of NodeJS's string concatenation behaving unexpectedly

I need help creating a string to print a specific message. "At position #[" + index + "][" + _subIndex + "] TLPHN_DVC_TYP " + + _telNum?.TelephoneDeviceType.toString() + " ,allowed &quo ...

Determining the accurate object from a nested type in Typescript is essential

I'm currently facing a challenge with Typescript in inferring the correct object within a switch case. I find it puzzling why my scenario works as expected with a union type but not with an object. Here is the code from the playground link: interface ...

When emitting an event multiple times in Angular, an error may occur where properties of undefined are unable to be read, particularly in relation to the "

I am encountering an issue with my event binding on a button, specifically (click)="onStart()". The problem arises when the event this.numEmitter is emitted for the first time in setInterval, after which I receive the error message ERROR TypeError: Cannot ...

Encountering the error message "Attempting to access a null or undefined value while populating an array within a loop in TypeScript."

I am relatively new to TypeScript and currently working on one of my initial projects in Microsoft Makecode Arcade. I am attempting to populate an array as a class property using a loop. class Game { grid: number[][] constructor() { for (l ...

Encountering an issue with importing typeDefs in Apollo Server (Typescript) from an external file

I decided to move the typeDefs into a separate file written in typescript and then compiled into another file. Upon doing so, I encountered the following error: node:internal/errors:490 ErrorCaptureStackTrace(err); ^ Error [ERR_MODULE_NOT_FOUND]: Una ...

The issue with ag-grid not displaying data when the column configurations are changed dynamically

I have been working with ag grid to display data in my component. I am fetching data through an API call and dynamically extracting the column names from the response to pass this information to the child component for display. However, the data is not sho ...