pla*_*rsh 4 polymer angular lit-element
我想在我的 Angular 应用程序中使用 Polymers LitElement。
为此,我在应用程序test.js的assets文件夹中创建了一个示例组件 ( ) ,并将其导入到index.html.
测试.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);Run Code Online (Sandbox Code Playgroud)
索引.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>Run Code Online (Sandbox Code Playgroud)
我安装lit-element在 comp-new 目录中,使用npm install --prefix ./ lit-element.
我也在npm install lit-element项目本身中做了一个,所以npm模块肯定是可用的。
但是,当我使用 运行我的 Angular 应用程序ng serve并导航到包含我的测试组件的 URL 时,我在 DOM 中找到了我的组件(使用检查器),但没有显示任何内容。此外,当我将 aconsole.log放入render函数时,我从未在浏览器中看到输出。所以看起来这个方法从未真正被调用过。
下面是它在 DOM 中的样子:
这是我的项目结构:
好吧。再次,解决我自己的问题,希望能帮助任何有类似问题的人;)
首先:我的方法不是最好的。我不建议将您的自定义元素放入资产文件夹。通常你会通过安装一个 npm 模块来获得你的自定义元素,所以我将这些组件移到了项目结构中。像这样,我也可以摆脱额外的 node_modules 并且导入变得更容易处理。
如何在 Angular 中使用 Lit Element 自定义组件:
npm install --save lit-elementsrc/app文件夹中为所有自定义组件创建一个文件夹(即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>
`;
}
}Run Code Online (Sandbox Code Playgroud)
注意我是如何遗漏这customElements.define('ti8m-test', Ti8mTestComponent)部分的。我们稍后会讲到。
您可以在代码中的任何位置定义自定义元素。我建议使用main.tsNgModule 或在要使用该元素的组件的构造函数中。
import {Ti8mTestComponent} from './app/custom-elements/ti8m/test';
...
customElements.define('ti8m-test', Ti8mTestComponent);
就是这样!您的 Lit 元素现在应该在您的应用程序中可见!:-)
笔记:
unknown在其代码中使用了 type ,这是 Typescript 3 引入的)targetin更改tsconfig.json为es2015. (否则你会遇到class constructors must be invoked with |new|控制台错误)玩得开心!我希望它有帮助。
| 归档时间: |
|
| 查看次数: |
3237 次 |
| 最近记录: |