Angular(8) - 创建特性组件 - 官方教程英雄指南之特性组件 (详细解说)

1 我们为什么需要特性组件, 为什么都是组件?

  • 此刻,HeroesComponent 同时显示了英雄列表和所选英雄的详情。
  • 把所有特性都放在同一个组件中,将会使应用“长大”后变得不可维护。 你要把大型组件拆分成小一点的子组件,每个子组件都要集中精力处理某个特定的任务或工作流
  • 组件,也就是意味,可以重复使用

2 我们创建HeroDetail子组件,让我们学习主从组件的使用,使用Angular cli 创建子组件, <hero-detail></hero-detail>

ng generate component hero-detail

3 小技巧分享,当你的angular在运行时,又不想停掉,又想安装组件怎么办? 可以使用vscode 的多终端, 这样就可以同时做很多事情了。

muti-bash

4 按照hero组件的用法 ,我们把详情代码移动到hero detail,然后调用,看看效果,让我们带着思考去学习,搞清楚下面的三个问题

4.1 我们将详情的HTML代码复制到 hero detail,会发现有error, 有error就对了,因为我们的详情里面都没有对应的对象,让我们思考一下

  • 对象是通过选择列表传入的,这就意味着我们需要提供接收对象的方法, 而这个方法应该在hero-detail.ts里面
  • 接收到对象后,我们还需要HTML渲染,这里也需要调整相应的HTML代码。
  • 组件与组件之间是如何通信的?

detail

4.2 增加Input 属性, 这个组件所做的只是通过 hero 属性接收一个英雄对象。

hero-detail.component.ts
//别忘记增加导入
import { Component, OnInit, Input } from '@angular/core';

import { Hero } from '../hero';


@Component({
  selector: 'app-hero-detail',
  templateUrl: './hero-detail.component.html',
  styleUrls: ['./hero-detail.component.css']
})
export class HeroDetailComponent implements OnInit {

//接收对象方法
  @Input() hero: Hero;

  constructor() { }

  ngOnInit(): void {
  }

}

4.3 将模板中的对象替换成hero

hero-detail.component.html
<div *ngIf="hero">

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

</div>

4.4 修改heroes模板, 可以看到已经应用上<app-hero-detail></app-hero-detail>

src/app/heroes/heroes.component.html
<h2>My Heroes</h2>

<ul class="heroes">
  <li *ngFor="let hero of heroes"
    [class.selected]="hero === selectedHero"
    (click)="onSelect(hero)">
    <span class="badge">{{hero.id}}</span> {{hero.name}}
  </li>
</ul>

<app-hero-detail [hero]="selectedHero"></app-hero-detail>

总结

  • 组件与组件之间是如何通信的?实际上仍然靠的是Angular的属性绑定方法, 在示例中 [hero]="selectedHero" 的作用是将 选中的hero 属性传递给 hero-detail中的属性 hero 。是不是很简单呢。
  • 你用 @Input 装饰器来让 hero 属性可以在外部的 HeroesComponent 中绑定。 什么是装饰器? 我们后面再说
posted @ 2020-08-14 19:13  三重罗生门  阅读(303)  评论(0编辑  收藏  举报