Using Angular custom web component throws error: The selector "app-root" did not match any elements
Angular web components already work with angular elements. The problem that I've had so far is that I couldn't have only a web component without an <app-root>
element at the same time. However, removing the boostrap
property of the app module entirely and instead adding
entryComponents: [AppComponent],
will make the error disappear. However, this will not initialize <app-root>
anymore, since we've removed it from the boostrap
part. Now we have to conditionally manually bootstrap the app with:
public ngDoBootstrap(appRef: ApplicationRef): void {
if (document.querySelector('app-root')) {
appRef.bootstrap(AppComponent);
}
}
This will do the trick.
For me, it seems like you forgot to add HeaderSearchComponent
in the declarations
part of your app.module.ts
.
Probably try it like this:
@NgModule({
declarations: [
AppComponent,
HeaderSearchComponent
],
imports: [
BrowserModule,
BrowserAnimationsModule,
HttpClientModule,
GraphQLModule,
SharedModule,
AppRoutingModule,
],
providers: [],
bootstrap: [AppComponent],
entryComponents: [HeaderSearchComponent],
})
export class AppModule {
constructor(private injector: Injector) {
const webComponent = createCustomElement(HeaderSearchComponent, {injector});
customElements.define('header-search', webComponent);
}
}
Also make sure your app.component.ts
has the following annotation:
@Component({
selector: 'app-root',
...
})
export class AppComponent { ... }