【发布时间】: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 装饰器,但我认为这不是最好的做法。
我的问题有什么解决办法吗?感谢所有帮助和投入。
【问题讨论】: