Angular CLI中的嵌套组件在第一级之后无法访问

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

我是Angular CLI的新手,我正在尝试根据我制作的较旧版本制作我的第一个Web。到目前为止,我可以在根组件内部嵌套和显示组件,但是从那时起,我不能在HTML中引用任何组件。

这是我的代码:

index.html

<!doctype html>
  <html lang="es">
    <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <title>Testing Angular</title>
      <base href="/">
      <link rel="icon" type="image/x-icon" href="favicon.ico">
    </head>
    <body>
      <app-root></app-root>
    </body>
  </html>

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';

import { AppComponent } from './app.component';
import { FirstComponent } from './first/first.component';

@NgModule({
  declarations: [AppComponent, FirstComponent],
  imports: [BrowserModule, AppRoutingModule],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ["./app.component.css"]
})

export class AppComponent {}

app.component.html

<section id="container">
  <app-first></app-first>
</section>

<router-outlet></router-outlet>

first.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { SecondComponent } from './second/second.component';

@NgModule({
  declarations: [SecondComponent],
  imports: [CommonModule]
})
export class FirstModule { }

first.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-first',
  templateUrl: './first.component.html',
  styleUrls: ["./first.component.css"]
})

export class FirstComponent {}

first.component.html

<div id="first">
  <app-second></app-second> <!-- This gives an error: it doesn't know whats Second Component -->
</div>

second.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

@NgModule({
  imports: [CommonModule],
  declarations: []
})
export class SecondModule { }

second.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-second',
  templateUrl: './second.component.html',
  styleUrls: ["./second.component.css"]
})

export class SecondComponent {}

second.component.html

<div id="second">
  <span>I'm second component!</span>
</div>

<app-second></app-second>参考给出错误。在Visual Studio中,代码甚至不在建议列表中。

javascript angular typescript angular-components
1个回答
1
投票

您必须将模块包括在某个地方,有些对您的SecondComponent不了解,请将FirstModule或SecondModule添加到您的AppModule中。查看Angular文档以获得更多策略https://angular.io/docs

  imports: [BrowserModule, AppRoutingModule, FirstModule],

通过添加带有要与其他模块共享的组件的导出来修改您的FirstModule。

exports: [SecondComponent] 
© www.soinside.com 2019 - 2024. All rights reserved.