我试图学习如何在我们的项目中使用 Angular 2 和 Material 2。我了解如何通过创建组件并将组件添加到 NgModule 声明中来将 md-toolbar 实现为组件。这很简单。但是我无法弄清楚如何将工具栏实现为模块中的组件。当我尝试这样做时,我收到以下错误。
我的代码如下:
工具栏模块:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ToolbarComponent } from './toolbar.component';
@NgModule({
imports: [
CommonModule
],
declarations: [
ToolbarComponent
],
providers: [
],
exports: [
ToolbarComponent
]
})
export class ToolbarModule {}
工具栏组件:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'toolbar',
templateUrl: './toolbar.component.html',
styleUrls: ['./toolbar.component.scss']
})
export class ToolbarComponent implements OnInit {
ngOnInit() {
console.log('Toolbar');
}
}
工具栏组件 HTML:
<md-toolbar>
<span>My Application Title</span>
</md-toolbar>
应用模块:
// Application Dependencies
import { NgModule, ApplicationRef } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpModule } from '@angular/http';
import { FormsModule } from '@angular/forms';
// Application Modules
import { MaterialModule } from '@angular/material';
import { ToolbarModule } from './modules/toolbar/toolbar.module';
// Application Components
import { AppComponent } from './app.component';
// Application Pages
import { HomeComponent } from './pages/home/home.component';
import { AboutComponent } from './pages/about/about.component';
// Application Services
import { routing } from './app.routing';
import { removeNgStyles, createNewHosts } from '@angularclass/hmr';
@NgModule({
imports: [
BrowserModule,
HttpModule,
FormsModule,
routing,
MaterialModule.forRoot(),
ToolbarModule
],
declarations: [
AppComponent,
HomeComponent,
AboutComponent
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {
constructor(public appRef: ApplicationRef) {}
hmrOnInit(store) {
console.log('HMR store', store);
}
hmrOnDestroy(store) {
let cmpLocation = this.appRef.components.map(cmp => cmp.location.nativeElement);
// recreate elements
store.disposeOldHosts = createNewHosts(cmpLocation);
// remove styles
removeNgStyles();
}
hmrAfterDestroy(store) {
// display new elements
store.disposeOldHosts();
delete store.disposeOldHosts;
}
}
应用组件:
import { Component } from '@angular/core';
import '../style/app.scss';
@Component({
selector: 'app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
})
export class AppComponent {
url = 'https://github.com/preboot/angular2-webpack';
constructor() {
// Do something with api
}
}
应用组件 HTML:
<header>
<toolbar></toolbar>
</header>
<main>
<h1>Hello</h1>
<router-outlet></router-outlet>
</main>
<footer>
<p>Footer</p>
</footer>
我觉得我错过了一些简单的事情,但无法弄清楚。任何帮助将不胜感激,因为这种将事物分成模块的模式对我来说很常见。