Angular Elements-无法将变量传递到我的Elements标签的@Input属性

时间:2020-11-10 16:33:12

标签: angular web-component angular-elements

我在这里需要一些帮助,我无法将变量传递给Elements标签的@Input变量。 如果我在代码中硬编码了一个caller-id =“ 123456”,它就可以正常工作;但是,如果我尝试将Angular组件的调用方ID作为变量传递,它将无法识别它。我基本上是在尝试检索组件的userId并将其传递给elements应用程序,以执行与userId相关的操作。任何帮助将不胜感激,谢谢。

Angular Elements应用 ts

export class AppComponent implements AfterContentInit {


 @Input() userId: string = "";
 @Input() userId2: string = "";


ngAfterContentInit() {
console.log(this.userId);
console.log(this.userId2);
}}

Angular Elements应用程序的app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { CUSTOM_ELEMENTS_SCHEMA, NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import {createCustomElement} from '@angular/elements';
import { Injector } from '@angular/core';


@NgModule({
 declarations: [
 AppComponent
 ],
 imports: [
  BrowserModule
  ],
  providers: [],
 entryComponents: [AppComponent],
 schemas: [CUSTOM_ELEMENTS_SCHEMA],
 bootstrap: [AppComponent]
 })
 export class AppModule { 
 constructor(injector: Injector) {
  const custom = createCustomElement(AppComponent, {injector});
  customElements.define('elements-app', custom)
 }

 ngDoBootstrap() {

 }
 }

当前的Angular组件,正在实现.js中的angular元素标签

实施Elements App的组件的

.ts文件

 constructor() {
 this.userId = "123456"
 }

组件的HTML文件实现了Elements应用

*does not work*- <elements-app user-id=userId></elements-app
*works*- <elements-app user-id="123456"></elements-app

使用角度元素.js文件标签的应用的app.module.ts

 @NgModule({
  declarations: [
   AppComponent
 ],
 imports: [
 BrowserModule,
 AppRoutingModule,
 BrowserAnimationsModule,
 HttpClientModule
 ],
 providers: [HttpClientModule, HttpClient],
 schemas: [CUSTOM_ELEMENTS_SCHEMA],
 bootstrap: [AppComponent]
  })
  export class AppModule { }

2 个答案:

答案 0 :(得分:0)

您需要在"变量周围加上引号caller_id,否则该变量将不起作用。以及围绕caller-id

的框绑定

更改 <elements-app caller-id=caller_id></elements-app>

<elements-app [caller-id]="caller_id"></elements-app>

查看更多信息 https://angular.io/guide/component-interaction#intercept-input-property-changes-with-a-setter

答案 1 :(得分:0)

您是否尝试过:<elements-app [attr.caller-id]="caller_id"></elements-app>