Polymer LitElement&Angular - 渲染永不调用,不显示任何内容

问题描述 投票:2回答:1

我想在我的Angular应用程序中使用Polymers LitElement。

为此,我在我的应用程序的test.js文件夹中创建了一个示例组件(assets),并将其导入index.html

test.js:

// Import the LitElement base class and html helper function
import { LitElement, html } from '../../../node_modules/lit-element/lit-element';

// Extend the LitElement base class
class Test extends LitElement {

  render(){
    return html`
      <h1>Test works!</h1>
    `;
  }
}
// Register the new element with the browser.
customElements.define('ti8m-test', Test);

index.html的:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>NgInAction</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">

  <script type="module" src="/assets/comp-new/default/src/ti8m/test.js"></script>

</head>
<body>
  <app-root></app-root>
</body>
</html>

我使用lit-element在comp-new目录中安装了npm install --prefix ./ lit-element

我也在项目中做了一个npm install lit-element,所以npm模块绝对可用。

但是,当我使用ng serve运行我的Angular应用程序,并导航到我包含我的测试组件的URL时,我在DOM中找到了我的组件(使用检查器),但没有显示任何内容。此外,当我将console.log放入render函数时,我从未在浏览器中看到输出。所以看起来这个方法实际上从未被调用过。

以下是它在DOM中的外观:

enter image description here

这是我的项目结构:

enter image description here

angular polymer lit-element
1个回答
1
投票

好的。再一次,解决我自己的问题,希望能帮助任何有类似问题的人;)

首先:我的方法不是最好的。我不建议将自定义元素放入assets文件夹中。通常,您可以通过安装npm模块来获取自定义元素,因此我将组件移动到项目结构中。像这样,我也可以摆脱额外的node_modules,导入更容易处理。

如何在Angular中使用Lit Element自定义组件:

  1. 在项目中安装lit-element:qazxsw poi
  2. npm install --save lit-element文件夹中为所有自定义组件创建一个文件夹(即src/app
  3. 创建你的组件(JS或TS,我选择了TS)

custom-components

请注意我是如何遗漏import { LitElement, html } from 'lit-element'; // Extend the LitElement base class // export the class, so it can be imported where it is needed export class Ti8mTestComponent extends LitElement { /** * Implement `render` to define a template for your element. * * You must provide an implementation of `render` for any element * that uses LitElement as a base class. */ render() { /** * `render` must return a lit-html `TemplateResult`. * * To create a `TemplateResult`, tag a JavaScript template literal * with the `html` helper function: */ console.log('test-component', this); return html` <h1>Test works!</h1> <p>For real though!</p> `; } }部分的。我们将在一秒钟内完成。

  1. 您可以在代码中的任何位置定义自定义元素。我建议使用customElements.define('ti8m-test', Ti8mTestComponent),一个NgModule,或者在你想要使用该元素的组件的构造函数中。 main.ts

而已!您的Lit Element现在应该在您的应用程序中可见! :-)

笔记:

  1. 我不得不更新到Angular 7,因为那是第一个使用Typescript> 3的版本,这是Lit Element npm模块所需要的。 (Lit Element在其代码中使用了import {Ti8mTestComponent} from './app/custom-elements/ti8m/test'; ... customElements.define('ti8m-test', Ti8mTestComponent);类型,由Typescript 3引入)
  2. 此外,我不得不将unknown中的target改为tsconfig.json。 (否则你会遇到es2015控制台错误)

玩得开心!我希望它有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.