【问题标题】:Angular won't recognize new componentAngular 无法识别新组件
【发布时间】:2020-07-27 01:19:14
【问题描述】:

我是 Angular 新手,我正在创建我的第一个英雄应用之旅(每个人都这样做)。但问题是角度无法识别新组件。就像它没有给出任何错误而不是在浏览器中呈现一样

更新:好的,我再次像 Wahab Shah 一样为我的应用程序提供服务,但这次是从 VS 代码终端而不是 Windows 终端,它现在可以工作了。非常感谢您的帮助

heroes.component.html

<h2>{{hero.name | uppercase}} Details</h2>
<div><span>id: </span>{{hero.id}}</div>
<div>
    <label>name:
    <input [(ngModel)]="hero.name" placeholder="name"/>
  </label>
</div>

heroes.component.ts

import { Component, OnInit } from '@angular/core';
import { Hero } from '../hero';

@Component({
  selector: 'app-heroes',
  templateUrl: './heroes.component.html',
  styleUrls: ['./heroes.component.css']
})
export class HeroesComponent implements OnInit {
  hero: Hero = {
    id: 1,
    name: 'Windstorm'
  };

  constructor() { }

  ngOnInit() {
  }

}

app-routing.module.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';


const routes: Routes = [];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

app.component.html

<h1>{{title}}</h1>
<app-heroes></app-heroes>

app.component.ts

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Tour of Heroes';

}

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms'; // <-- NgModel lives here

import { AppComponent } from './app.component';
import { HeroesComponent } from './heroes/heroes.component';

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

hero.ts

export interface Hero {
  id: number;
  name: string;
}

【问题讨论】:

  • 您刚刚创建了新组件吗?
  • 是的,从终端通过命令“ng generate component heros”
  • 你能分享你的代码吗?没有代码无法回答
  • ng 再次为您的应用程序提供服务,或者在这种情况下使用您新创建的组件在其父组件中的选择器。你可以粘贴你的代码sn-p吗?通过这种方式,我们将能够更好地为您提供帮助。
  • 你是否在模块中声明了组件?

标签: angular


【解决方案1】:

ng 再次为您的应用提供服务,或者如果是这种情况,则在其父组件中使用您新创建的组件的选择器。

大多数情况下,在添加新组件或模块后,应用程序不会呈现它。只需重新服务即可。

【讨论】:

    【解决方案2】:

    问题可能是这样的,

    1. 您尚未为该组件声明任何路由
    2. 您尚未在 app.component.html 页面中添加该新组件的应用选择器。

    其中任何一个都可能导致新组件无法在浏览器中呈现。

    【讨论】:

    • 您像建议的 cmets 之一那样重新启动您的 Angular 应用程序。同时按 F12 并观察控制台中是否出现任何错误
    • 做到了并且它的工作。问题是我正在从 Windows 终端编译我的应用程序。现在我是从 VS 代码终端做的,它工作正常。虽然看起来很奇怪
    猜你喜欢
    • 2023-03-06
    • 2018-08-01
    • 1970-01-01
    • 2020-02-28
    • 2018-03-11
    • 1970-01-01
    • 2017-02-15
    • 2020-07-21
    • 2020-12-11
    相关资源
    最近更新 更多