【问题标题】:How to get component's variable in Angular 8 Web Components如何在 Angular 8 Web Components 中获取组件的变量
【发布时间】:2020-05-06 20:36:38
【问题描述】:

我在版本 8 中使用 Angular Web 组件。我想从 index.html 中获取组件的属性。这是我所拥有的;

有一个组件具有名为 componentNames

的属性
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-component-name-provider',
  templateUrl: './component-name-provider.component.html',
  styleUrls: ['./component-name-provider.component.css']
})
export class ComponentNameProviderComponent implements OnInit {

  public componentNames: string[] = [];

  constructor() { }

  ngOnInit() {
    this.componentNames = ['name1', 'name2'];
  }
}

我有 index.html,我想从这里获取 componentNames(上面提到的)属性。

<app-component-name-provider></app-component-name-provider>
<script>
    const el = document.querySelector('app-component-name-provider');
    el.componentNames // here I tried to perform but did not work, el is null
</script>

如果需要,我也会删除 app.module.ts;

import { Injector, NgModule } from '@angular/core';
import { createCustomElement } from '@angular/elements';
import { FormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';
import { ComponentNameProviderComponent } from './component-name-provider/component-name-provider.component';

@NgModule({
  declarations: [
    ComponentNameProviderComponent
  ],
  imports: [
    BrowserModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [],
  entryComponents: [
    ComponentNameProviderComponent
  ]
})
export class AppModule {
  constructor(private injector: Injector) {
  }

  ngDoBootstrap() {
    const componentNameProviderComponentCustomElement = createCustomElement(ComponentNameProviderComponent, { injector: this.injector });
    customElements.define('app-component-name-provider', componentNameProviderComponentCustomElement);
  }
}

我试图解释我所拥有的。我正在寻找一种从 index.html 获取 componentNames 属性的方法。正如我上面尝试的那样,我无法通过获取 document.querySelector

来获取变量

我知道我可以在事件发射器上使用 @Output 装饰器,但我认为这不是最好的做法。

我的问题有什么解决办法吗?感谢所有帮助和投入。

【问题讨论】:

    标签: angular angular8


    【解决方案1】:

    您可以使用@ViewChild 来获取componentNames 属性。 您必须将 localReference 添加到您的组件,如下所示。

    <app-component-name-provider #testName></app-component-name-provider>
    
    @ViewChild('testName', {static:true}) testName;
    
      ngAfterViewInit() {
        console.log(this.testName); // you will get your component properties here
      }
    

    答案链接: https://stackblitz.com/edit/angular-ubzhfd?file=src%2Fapp%2Fapp.component.ts

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-03
      • 1970-01-01
      • 1970-01-01
      • 2020-10-04
      • 2019-12-26
      • 1970-01-01
      相关资源
      最近更新 更多