Angular 13,AppModule 中的自定义管道不能在子模块中使用

问题描述 投票:0回答:1

在我的 Angular 应用程序中,我有一个自定义管道,将其放在 AppModule 中的“声明”和“导出”中。我有一个子模块“HomeModule”,带有一个 HomeComponent。现在,我在 HomeComponent 中使用自定义管道,但收到错误“NG8004:找不到名称为“rootEmptyPipe”的管道。”

我知道好的做法是将这个管道放在“SharedModule”中并将其导入“HomeModule”中,但就我而言,**至少现在,我没有“SharedModule”。请至少暂时避免朝那个方向走。 **

下面是示例代码,谢谢!

我期望没有错误,因为我相信在 AppModule 级别定义的自定义管道应该在子模块中看到。

- AppModule
@NgModule({
  imports: [
    CommonModule,
    BrowserModule,
    FormsModule,
    ReactiveFormsModule,
    HttpClientModule,
.....
    HomeModule, <-------------------------- import HomeModule
    BrowserAnimationsModule,
    AppRoutingModule, 
  ],
  declarations: [RootEmptyPipe, <----------------- delare custom Pipe
TestComponent, 
AppComponent],
  exports: [RootEmptyPipe], <-----------------export custome Pipe
  bootstrap: [AppComponent],
})
export class AppModule {}


- HomeModule

@NgModule({
  declarations: [
    HomeComponent,
....
    TestPipeComponent, <------------------ component to test custom Pipe
  ],
  imports: [
    CommonModule,
    FormsModule,
    ReactiveFormsModule,
    HttpClientModule,
    BrowserModule,
....
    RouterModule.forChild(routes),
  ],
  exports: [],
})
export class HomeModule {}

- TestPipeComponent 

@Component({
  selector: 'app-test-pipe',
  template: `<h1>{{ 'Hello Home Test Pipe Component' | rootEmptyPipe }}</h1>`, <------ **error here!!!**
  styleUrls: ['./test-pipe.component.scss'],
})
export class TestPipeComponent implements OnInit, OnDestroy {
  private onDestroy$: Subject<boolean> = new Subject();

  constructor(private httpClient: HttpClient) {}

  ngOnInit(): void {}


  ngOnDestroy(): void {
    this.onDestroy$.next(true);
    this.onDestroy$.complete();
  }
}

- RootEmptyPipe, only an example


@Pipe({
  name: 'rootEmptyPipe'
})
export class RootEmptyPipe implements PipeTransform {
  public transform(value: any, ...args: any[]): string {
    if (!value || value.length < 1) {
      if (args.length < 1) {
        return '-';
      } else {
        return args[0];
      }
    }
    return value;
  }
}

angular pipe
1个回答
0
投票

就我而言,即目前不能选择使用 SharedModule,解决方案是将自定义管道声明为独立:true,然后将其“导入”到 HomeModule 中。 希望这可以帮助处于相同情况的其他人。 再次强调,如果您的情况允许,“将其放入 SharedModule 中”是最佳实践。

© www.soinside.com 2019 - 2024. All rights reserved.