在 Angular 中显示列表通常涉及使用 *ngFor 指令,该指令允许你循环遍历数组并在模板中显示其元素。以下是一个简单的步骤,帮助你在 Angular 项目中显示英雄列表。

1. 创建英雄服务:

   如果你还没有创建英雄服务,你可以使用之前的例子中的 HeroService。

2. 创建英雄列表组件:

   在 src/app 目录下创建一个 hero-list 组件,该组件将显示英雄列表。
   // src/app/hero-list/hero-list.component.ts
   import { Component } from '@angular/core';
   import { Hero } from '../hero.model';
   import { HeroService } from '../hero.service';

   @Component({
     selector: 'app-hero-list',
     template: `
       <h2>Hero List</h2>
       <ul>
         <li *ngFor="let hero of heroes">{{ hero.name }}</li>
       </ul>
     `,
     styles: [],
   })
   export class HeroListComponent {
     heroes: Hero[] = [];

     constructor(private heroService: HeroService) {
       this.heroes = heroService.getHeroes();
     }
   }

3. 在父组件中使用英雄列表组件:

   在你的父组件(比如 app.component.ts)中使用 app-hero-list 组件。
   // src/app/app.component.ts
   import { Component } from '@angular/core';

   @Component({
     selector: 'app-root',
     template: `
       <h1>Hero Tour</h1>
       <app-hero-list></app-hero-list>
     `,
     styles: [],
   })
   export class AppComponent {}

4. 在模块中导入并声明组件:

   在你的模块中(通常是 app.module.ts)导入并声明这两个组件。
   // src/app/app.module.ts
   import { NgModule } from '@angular/core';
   import { BrowserModule } from '@angular/platform-browser';
   import { HeroListComponent } from './hero-list/hero-list.component';

   @NgModule({
     declarations: [HeroListComponent],
     imports: [BrowserModule],
     bootstrap: [HeroListComponent],
   })
   export class AppModule {}

   请注意,HeroListComponent 可能需要在实际应用中的其他组件中使用,而不仅仅是在 AppComponent 中。

5. 运行应用:

   在命令行中运行 ng serve,然后在浏览器中打开 http://localhost:4200/,你应该能够看到包含英雄列表的页面。

这就是一个简单的例子,帮助你在 Angular 中显示英雄列表。在实际应用中,你可能会使用路由导航到不同的页面,从后端获取英雄数据,或者添加更多复杂的逻辑。


转载请注明出处:http://www.pingtaimeng.com/article/detail/5022/Angular