[英]Defining Angular Component inline, in routes?
目前,我的路線定義如下:
export const myRoutes: Routes = [
{ path: '', component: MyComponent },
];
在我的模塊中帶有RouterModules.forChild(myRoutes)
。
如何以內聯方式定義此組件以及完整的內聯模板?
尋找類似的東西:
{ path: '/foo', component: { template: '<h1>foo</h1>' } }
編輯:嘗試
{
path: '/test', component: Component({
template: '<h1>Foo</h1>',
styles: [':host {color: red}']
})(class {})
}
但是出現了這個錯誤:
錯誤:組件class_1不是任何NgModule的一部分,或者該模塊尚未導入到您的模塊中。
使用: [MyComponent, ...declarations]
其中, declarations
是過濾myRoutes
的const
,它可以工作,但僅適用於ng serve
。 ng build --prod
錯誤:
錯誤:模塊聲明了意外的值'null'
import { AfterViewInit, Compiler, Component, Input,
NgModule, OnInit, ViewChild, ViewContainerRef } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-my',
templateUrl: './my.component.html',
styles: []
})
export class MyComponent implements OnInit, AfterViewInit {
@Input() template: string;
@Input() styles: string[];
@ViewChild('container', { read: ViewContainerRef }) container: ViewContainerRef;
constructor(private route: ActivatedRoute, private compiler: Compiler) {}
ngOnInit() {
this.route.data
.subscribe((data: {template: string, styles?: string[]}) => {
this.template = data.template;
this.styles = data.styles || [];
});
}
// https://github.com/angular/angular/issues/15275#issuecomment-434793800
ngAfterViewInit() {
// Must clear cache.
this.compiler.clearCache();
// Define the component using Component decorator.
const component = Component({
template: this.template,
styles: this.styles
})(class {});
// Define the module using NgModule decorator.
const module = NgModule({
declarations: [component]
})(class {});
// Asynchronously (recommended) compile the module and the component.
this.compiler.compileModuleAndAllComponentsAsync(module)
.then(factories => {
// Get the component factory.
const componentFactory = factories.componentFactories[0];
// Create the component and add to the view.
const componentRef = this.container.createComponent(componentFactory);
});
}
}
import { Routes } from '@angular/router';
import { MyComponent } from './my.component';
export const myRoutes: Routes = [
{ path: '', component: MyComponent,
data: { template: 'hello' } },
{ path: 'foo', component: MyComponent,
data: { template: 'foo', styles: [':host {color: red}'] } },
{ path: 'bar', component: MyComponent,
data: { template: 'bar', styles: [':host {color: blue}'] } },
{ path: 'can', component: MyComponent,
data: { template: 'can', styles: [':host {color: green}'] } }
];
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule } from '@angular/router';
import { MyComponent } from './my.component';
import { myRoutes } from './my.routes';
@NgModule({
declarations: [MyComponent],
imports: [CommonModule, RouterModule, RouterModule.forChild(myRoutes)],
providers: []
})
export class MyModule {}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.