[英]Can't I use a component defined in a file other than app.component.ts in HTML directly?
I am facing difficulty in using a component defined in a file named navigation.component.ts directly on HTML Page. 我直接在HTML页面上使用在名为navigation.component.ts的文件中定义的组件时遇到了困难。 The same component works fine if I use it under template of a component defined on app.component.ts.
如果在app.component.ts上定义的组件模板下使用同一组件,则该组件可以正常工作。
Contents of app.module.ts app.module.ts的内容
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { NavigationComponent} from './shared/navigation.component';
@NgModule({
imports: [BrowserModule],
declarations: [AppComponent, NavigationComponent],
bootstrap: [ AppComponent ]
})
export class AppModule { }
Contents of navigation.component.ts navigation.component.ts的内容
import { Component } from '@angular/core';
@Component({
selector: 'navigation',
templateUrl: '/views/shared/navigation.html'
})
export class NavigationComponent {
userName: string = 'Anonymous';
}
Contents of app.component.ts app.component.ts的内容
import { Component } from '@angular/core';
@Component({
selector: 'main-app',
template: '<navigation></navigation><h1>{{pageTitle}}</h1>'
})
export class AppComponent {
pageTitle: string = 'Portal 2.0';
}
Contents of index.html index.html的内容
<body>
<main-app></main-app>
</body>
The above works and renders menus on top but when I try to use <navigation>
directly (given below) it doesn't render it, doesn't show any errors either. 上面的作品在顶部显示并渲染菜单,但是当我尝试直接使用
<navigation>
(如下所示),它不会渲染它,也不会显示任何错误。
<body>
<navigation></navigation>
</body>
Am I doing something wrong? 难道我做错了什么?
And the bigger question is how I go debugging issues like this? 更大的问题是我该如何调试此类问题?
Yes you can use web components. 是的,您可以使用Web组件。 Add all the components that you want to load to entrycomponents.
将要加载的所有组件添加到entrycomponents。 Using createCustomElement you can create elements and use their selector anywhere.
使用createCustomElement可以创建元素并在任何地方使用它们的选择器。
import { BrowserModule } from '@angular/platform-browser';
import { NgModule, Injector } from '@angular/core';
import { createCustomElement } from '@angular/elements';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule
],
providers: [],
entryComponents: [AppComponent]
})
export class AppModule {
constructor(private injector: Injector) {
console.log('Elements is loaded: Activation');
this.registerComponent('metro-activation-loader', AppComponent);
}
public ngDoBootstrap(): void {
console.log('Elements is loaded: Activation ngDoBootstrap');
}
// tslint:disable-next-line:no-any
private registerComponent(name: string, component: any): void {
const injector = this.injector;
const customElement = createCustomElement(component, { injector });
customElements.define(name, customElement);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.