简体   繁体   English

如何将参数从 html 页面传递到 angular 自定义元素

[英]How to pass a parameter from html page to angular custom element

I've created an angular custom element from an angular component that I want call from a normal html page.我从一个 angular 组件创建了一个 angular 自定义元素,我想从一个普通的 html 页面调用它。

The component requires a parameter, which works when it's called as a component from within an angular project, but I cannot figure out how to pass the parameter from the html tag to the custom element.该组件需要一个参数,该参数在 angular 项目中作为组件调用时起作用,但我不知道如何将 html 标记中的参数传递给自定义元素。

Current I'm trying to use:当前我正在尝试使用:

  @Input() crs: string

in the component and:在组件中,并且:

<station-info crs="btn"></station-info>

in the html tag, but the crs never makes it into the component.在 html 标签中,但 crs 从未进入组件。

What I'd like to know is the correct way to pass the parameter from the html tag to the component after it has been converted to a custom element?我想知道的是在转换为自定义元素后将参数从 html 标签传递给组件的正确方法?

I eventually worked it out, so here's my write up of how to do it:我最终解决了这个问题,所以这是我写的如何做到这一点:

How To Create And Use A Custom Element如何创建和使用自定义元素

  1. Install angular elements安装 angular 元件

    ng add @angular/elements ng 添加@angular/元素

    npm i --save-dev concat fs-extra npm i --save-dev concat fs-extra

  2. In tsconfig.json, ensure target uses es2015 or newer:在 tsconfig.json 中,确保目标使用 es2015 或更新版本:

    "target": "es2015", “目标”:“es2015”,

  3. Add the following to app.module.ts将以下内容添加到 app.module.ts

==> Add the imports ==> 添加导入

import  { Injector} from '@angular/core';
import  { createCustomElement } from '@angular/elements';

==> Add the component to the bootstrap array ==> 将组件添加到引导数组

bootstrap: [AppComponent]

==> Change the constructor to the following: ==> 将构造函数更改为以下内容:

  constructor(
    private injector: Injector
  ) {
    const el = createCustomElement(AppComponent, { injector });
    customElements.define('station-info', el); // <-- 'station-info' is the name of the html tag you want to use
  }

  ngDoBootstrap() {}
  1. To enable parameters to be passed from the HTML tag to the custom element, do the following steps要使参数能够从 HTML 标记传递到自定义元素,请执行以下步骤

In app.component.ts:在 app.component.ts 中:

  • Accept any input parameters using @Input and change any parameters retrieved from ActivatedRoute to use the @Input variables使用 @Input 接受任何输入参数并更改从 ActivatedRoute 检索到的任何参数以使用 @Input 变量

Note: To ensure the input variables on the HTML tag are bound to the @Input properties, you must pass the tag attribute name to the @Input method ie @Input('crs') (see example below)注意:为确保 HTML 标签上的输入变量绑定到@Input 属性,您必须将标签属性名称传递给@Input 方法,即@Input('crs')(参见下面的示例)

eg Delete these:例如删除这些:

this.crs = this.activatedRouteService.snapshot.params.crs.toLowerCase();
this.stationName = this.activatedRouteService.snapshot.params.stationName.toLowerCase();

Add these (insert after export class):添加这些(在导出类之后插入):

@Input('crs') crs: string
@Input('stationName') stationName: string;
  • In ngOnInit(), navigate to the component, passing on any input parameters: eg在 ngOnInit() 中,导航到组件,传递任何输入参数:例如

    this.router.navigateByUrl('/station-details/' + this.crs + '/' + this.stationName); this.router.navigateByUrl('/station-details/' + this.crs + '/' + this.stationName);

In app-routing.module.ts在 app-routing.module.ts

Delete (so there is no automatic routing):删除(所以没有自动路由):

{ path: '', redirectTo: 'station-details', pathMatch: 'full' },

Pass any parameters on the appropriate path:在适当的路径上传递任何参数:

{ path: 'station-details/:crs/:stationName', component: StationDetailsComponent,

In the custom HTML tag在自定义 HTML 标签中

Add the parameters as follows:添加参数如下:

<station-info crs="btn" station-name="Brighton" client="tl" has-template="true"></station-info>
  1. Create a build-component.js file in the root folder with the following content Note: dist/dev is the folder structure automatically created by the compiler在根文件夹下创建一个build-component.js文件,内容如下注:dist/dev是编译器自动创建的文件夹结构

    const fs = require('fs-extra'); const fs = require('fs-extra');

    const concat = require('concat'); const concat = require('concat');

    build = async () =>{ const files = [ './dist/dev/runtime.js', './dist/dev/polyfills.js', './dist/dev/scripts.js', './dist/dev/main.js' ]; build = async () =>{ const files = [ './dist/dev/runtime.js', './dist/dev/polyfills.js', './dist/dev/scripts.js', '. /dist/dev/main.js' ];

    await fs.ensureDir('station-info');等待 fs.ensureDir('station-info'); // <-- Use the same name here as in customElements.define // <-- 此处使用与 customElements.define 中相同的名称

    await concat(files, 'station-info/station-info.js');等待连接(文件,'station-info/station-info.js'); // <-- this is where you want to save the resulting files } // <-- 这是你想要保存结果文件的地方 }

    build();建造();

  2. Compile and concatenate the resulting files编译并连接生成的文件

==> Add build-component.js script to package.json ==> 将 build-component.js 脚本添加到 package.json

"scripts": {
  "build:component": "ng build --configuration production --output-hashing none && node build-component.js",
}

==> Run the script ==> 运行脚本

npm run build:component
  1. To use the custom element, add the following to an html page Note: You also have to ensure any external assets that the custom element requires are present eg images and files要使用自定义元素,请将以下内容添加到 html 页面 注意:您还必须确保存在自定义元素所需的任何外部资产,例如图像和文件

  • If you want to pass a parameter:如果要传递参数:

You can use property binding to pass data from parent to child.您可以使用属性绑定将数据从父级传递给子级。

Like so, Use property binding to bind the item property in the child to the currentItem property of the parent.像这样,使用属性绑定将子项中的项属性绑定到父项的 currentItem 属性。

<app-item-detail [item]="currentItem"></app-item-detail>

In the parent component class, designate a value for currentItem:在父组件 class 中,为 currentItem 指定一个值:

export class AppComponent {
  currentItem = 'Television';
}

Link to angular docs: https://angular.io/guide/inputs-outputs链接到 angular 文档: https://angular.io/guide/inputs-outputs

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM