Определение углового компонента inline, в маршрутах? - PullRequest
0 голосов
/ 02 декабря 2018

В настоящее время я определяю свои маршруты следующим образом:

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 isне является частью какого-либо модуля NgModule или модуль не был импортирован в ваш модуль.

Использование: [MyComponent, ...declarations] где declarations - это const от фильтрации myRoutes, работает, но только дляng serve.ng build --prod ошибки с:

ОШИБКА в: неожиданное значение 'null', объявленное модулем

1 Ответ

0 голосов
/ 03 декабря 2018

my.component.ts

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);
      });
  }
}

my.routes.ts

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}'] } }
];

my.module.ts

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 {}
...