错误



我有一个NavbarComponent和FooterComponent,我想移到SharedModule中,以保持根app.module的干净。

应用程序模块

import { AdminComponent } from './admin/admin.component';
// import { NavbarComponent } from './navbar/navbar.component';
// import { FooterComponent } from './footer/footer.component';

// Modules
import { DashboardModule } from './dashboard/dashboard.module';
import { HomeModule } from './home/home.module';

@NgModule({
  declarations: [
    AppComponent,
    LoginComponent,
    RegisterComponent,
    PasswordResetComponent,
    ResetPasswordComponent,
    AdminComponent,
    // NavbarComponent,
    // FooterComponent,

share.module

但是,一旦我将这些组件移到此处,并正确更新了它们的路径./-> ../,应用程序就会中断。
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

import { NavbarComponent } from '../navbar/navbar.component';
import { FooterComponent } from '../footer/footer.component';
import { TermsComponent } from './terms.component';
import { PageNotFoundComponent } from './not-found.component';
import { PrivacyPolicyComponent } from './privacy-policy.component';

@NgModule({
  imports: [
    CommonModule
  ],
  declarations: [
    NavbarComponent,
    FooterComponent,
    TermsComponent,
    PageNotFoundComponent,
    PrivacyPolicyComponent
  ]
})
export class SharedModule { }

navbar.component.ts
import { Component, OnInit } from '@angular/core';
import { AuthService } from '../auth.service';
import { environment } from '../../environments/environment';

@Component({
  selector: 'app-navbar',
  templateUrl: './navbar.component.html',
  styleUrls: ['./navbar.component.scss']
})
export class NavbarComponent implements OnInit {
  isHidden = true;
  oauthUrl = this.authService.generateOauthUrl();

  constructor(public authService: AuthService) { }

  ngOnInit() {
  }

  logout() {
    sessionStorage.clear();
  }
}

然后用 navbar.component.html 中的[ngbCollapse]行几行
<div *ngIf="!authService.isLoggedIn()" class="collapse navbar-collapse" id="navbarSupportedContent" [ngbCollapse]="isHidden">

我认为这与相对路径有关,有什么想法吗?

最佳答案

要在Angular模板中使用ng-bootstrap组件和指令,您需要导入NgbModule。对于您的情况,应将其导入SharedModule中。另外,为了在应用程序的其他部分中使用共享的组件,您应该从SharedModule导出它们,并在使用组件时将SharedModule导入模块中。

shared.module.ts

...
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';

@NgModule({
  imports: [
    CommonModule,
    NgbModule
  ],
  declarations: [
    NavbarComponent,
    FooterComponent,
    TermsComponent,
    PageNotFoundComponent,
    PrivacyPolicyComponent
  ],
  exports: [
    NavbarComponent,
    FooterComponent,
    TermsComponent,
    PageNotFoundComponent,
    PrivacyPolicyComponent
  ]
})
export class SharedModule { }

app.module.ts
import { SharedModule } from './shared/shared.module';
...

@NgModule({
  imports: [
    SharedModule,
    ...
  ],
  ...
})

注意:如果要在ng-bootstrap之外的模板中使用SharedModule组件和指令,则应将NgbModule添加到exportsSharedModule中。

09-25 18:53