Is there a preferred method for correctly nesting components?

It may seem like a simple question, but I couldn't find the answer in the documentation or code examples.

Consider this example:

import { FlowIdentification } from "./flow-identification";

@customElement("bb-flow")
export class Root extends LitElement {
//...
 render() {
    return html`<div>${new FlowIdentification()}</div>` 

// Is this approach better for typing?

However, this alternative method also works and is potentially more recommended:

import "./flow-identification";

@customElement("bb-flow")
export class Root extends LitElement {
//...
 render() {
    return html`<div><flow-identification></flow-identification></div>` 

Doesn't the second method lose typings? And does the first method even make sense? It's confusing.

Having a "How to nest components" section in the documentation would be helpful. :)

Answer №1

Custom elements, known as lit elements, can be created using any browser API for generating HTML. This allows you to not only create your element but also nest it within another element. These custom elements behave similarly to native browser elements by default and can be enhanced with additional tooling if desired.

There are various methods for creating these elements, each with its own tradeoffs in terms of typing. The recommended approach is to use the second example provided below. Typing can be optionally enforced utilizing tools like lit-plugin.

Creating Lit Elements (and any HTML elements)

Using Static HTML - Declarative API

<!-- Element in an HTML context (such as an HTML file, markdown, or an HTML tag function) -->
<flow-identification></flow-identification>

<!-- Nested Example -->
<div><flow-identification></flow-identification></div>

Alternatively, you can utilize Lit's html tag function:

const template = html`<div><flow-identification></flow-identification></div>`;

If needed, types can be introduced through tools like the lit-plugin. More information can be found here:

Using Imperative DOM APIs

// `el` will have correct typings in TypeScript when present on HTMLElementTagNameMap
const el = document.createElement('flow-identification');
document.body.append(el); // Example of nesting within `body` element.

It's worth noting that your FlowIdentification element will be typed if the specified code snippet is added to your TypeScript source code. Refer to this documentation link for more details: [documentation link]

declare global {
  interface HTMLElementTagNameMap {
    "flow-identification": FlowIdentification;
  }
}

You can also utilize innerHTML, although it won't provide typing:

document.body.innerHTML = "<div><flow-identification></flow-identification></div>";

As previously mentioned, constructing a custom element through its constructor is possible, but the element must already be defined in the custom elements registry. Reference available here: [reference]

const el = new FlowIdentification();

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

`Typescript does not adhere to the specified type when used inside a for loop with a local

This code snippet declares a variable venuelist of type Venue array and initializes it as an empty array. The type Venue has a property named neighborhood. There is a for loop that iterates through the venuelist array and checks if the neighborhoods matc ...

Guide to creating JSDoc for a TouchEvent handler

Looking to improve my shorter-js codebase with JSDoc for TypeScript definitions, but hitting a roadblock. I've implemented the on() function using Element.addEventListener, working well so far. However, when passing a TouchEvent as a parameter for an ...

A guide on utilizing the useEffect hook to dynamically update a button icon when hovering over it in a React application

Is it possible to change the icon on a button when hovering using useEffect? <Button style={{ backgroundColor: "transparent" }} type="primary" icon={<img src={plusCart} />} onCl ...

Transfer only designated attributes to object (TS/JS)

Is it feasible to create a custom copy function similar to Object.assign(...) that will only copy specific properties to the target? The code snippet I have is as follows: class A { foo?: string; constructor(p: any) { Object.assign(this, p ...

There is a WARNING occurring at line 493 in the file coreui-angular.js located in the node_modules folder. The warning states that the export 'ɵɵdefineInjectable' was not found in the '@angular/core' module

I encountered a warning message while running the ng serve command, causing the web page to display nothing. Our project utilizes the Core Ui Pro Admin Template. Here is the list of warning messages: WARNING in ./node_modules/@coreui/angular/fesm5/coreu ...

Remove the export statement after transpiling TypeScript to JavaScript

I am new to using TypeScript. I have a project with Knockout TS, and after compiling it (using the Intellij plugin to automatically compile ts to js), this is my sample.ts file: import * as ko from "knockout"; ko; class HelloViewModel { language: Kn ...

Implementing strict typing in Twitter widget to eliminate issues with accessing members

I'm struggling to properly type my Twitter widget in TypeScript. Currently, I am encountering several errors such as: ESLint: Unsafe call of an any typed value.(@typescript-eslint/no-unsafe-call) ESLint: Unsafe member access .catch on an any value.(@ ...

Creating a custom button for exporting a high chart to CSV

My Angular project involves exporting a chart to various formats, such as png, jpeg, pdf, and SVG. However, I am encountering an issue when trying to export the chart as CSV or . I have attempted the following code: this.lineChart.chart.downloadCSV(); //F ...

Error: _CoalescedStyleScheduler provider not found

I'm currently attempting to follow a tutorial on Angular Material pagination, but I keep encountering this error: ERROR Error: Uncaught (in promise): NullInjectorError: StaticInjectorError(AppModule)[MatTable -> _CoalescedStyleScheduler]: Static ...

Due to the feature in VISUAL STUDIO CODE that presents folders and subfolders at the same level

While working on my Angular project, I encountered an issue with creating a subfolder within a folder. Despite trying the same process in Windows Explorer, I faced the same problem of them appearing on the same level. What could be causing this discrepan ...

The function signature '({ articles }: Props) => JSX.Element' does not match the type 'NextPage<{}, {}>'

Recently, I've decided to delve into the world of React.js and Next.js after being familiar with Vue.js. Encountering a peculiar typescript error has left me scratching my head, but surprisingly, the code actually compiles despite Visual Studio Code w ...

Tips on updating TypeScript to a higher major version

Despite upgrading all packages, deleting node_modules and package-lock.json, and reinstalling with npm install, the typescript runtime in my git repo is still showing version 4.9.5. How can I update the tsc version to be higher than 5.0? $ npx tsc --versi ...

React Typescript - Unexpected character ',' encountered at line 1005

Currently, I am utilizing Typescript within a React application that integrates with Graphql. Encountering an error: ',' expected.ts(1005) After researching possible solutions, most suggest that the issue might be due to using an outdated ve ...

Utilize the power of Wikitude within an Angular 2 application

I am currently working on integrating Wikitude Architect View in Angular 2 by referring to the code at this link. My goal is to implement this code in an Angular 2 compatible way. import * as app from 'application'; import * as platform from & ...

Anticipating the desired data types for Jasmine arguments

Lately, I've been in the process of upgrading my Angular version from 10 to 13 in order to utilize TypeScript 4.6. However, during this upgrade, I made some errors with types in my tests and I'm wondering if others have encountered similar issues ...

What is the necessity behind keeping makeStyles and createStyles separate in Material UI with TypeScript?

Dealing with TypeScript issues in Material UI has been a frequent task for me, and I find it frustrating that styling components requires combining two different functions to create a hook every time. While I could use a snippet to simplify the process, it ...

I am looking for guidance on how to effectively utilize a JSON object that is stored in the constructor of my component, particularly when triggering

Below is the object I have in my constructor. I am passing a value from a previous component to the one below. I receive the item json object, but I need to use it when I click. constructor(public navCtrl: NavController, public navParams: NavParams) { ...

The Nestjs ClientMqtt now has the capability to publish both pattern and data to the broker, as opposed to just sending

I am currently utilizing Nestjs for sending data to a Mqtt Broker. However, I am facing an issue where it sends both the pattern and data instead of just the data in this format: { "pattern": "test/test", "data": " ...

Creating a factory class in Typescript that incorporates advanced logic

I have come across an issue with my TypeScript class that inherits another one. I am trying to create a factory class that can generate objects of either type based on simple logic, but it seems to be malfunctioning. Here is the basic Customer class: cla ...

Refreshing an Angular page when navigating to a child route

I implemented lazy loading of modules in the following way: { path: 'main', data: {title: ' - '}, component: LandingComponent, resolve: { images: RouteResolverService }, children: [ { path: '', redirectTo: 'home&apo ...