欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

详解Angular6学习笔记之主从组件

程序员文章站 2023-01-10 20:08:38
主从组件 继学习笔记6,现在可以在页面上显示一个数组,但是原则上不能将所有特性放在同一个组件中,因为如果将所有特性放在同一个组件中,当特性特别多时,组件就变得不好维护...

主从组件

继学习笔记6,现在可以在页面上显示一个数组,但是原则上不能将所有特性放在同一个组件中,因为如果将所有特性放在同一个组件中,当特性特别多时,组件就变得不好维护了。所以要将大型组件拆分为多个小型组件,使每一个小型组件集中处理某一个特性任务或者工作流,而且这样也便于维护。

这次要将学习笔记6中的查看hero详情,放置在一个新的,独立,可复用的组件中,集中在新的组件管理和维护hero详情的信息。

1.创建一个新的组件

使用 angular cli 生成一个名叫 hero-detail 的新组件。

wjydemacbook-pro:demo wjy$ ng generate component hero-detail
create src/app/hero-detail/hero-detail.component.css (0 bytes)
create src/app/hero-detail/hero-detail.component.html (30 bytes)
create src/app/hero-detail/hero-detail.component.spec.ts (657 bytes)
create src/app/hero-detail/hero-detail.component.ts (288 bytes)
update src/app/app.module.ts (548 bytes)

这样就生成了 herodetailcomponent 组件所需要的文件,并把它声明在 appmodule 中。

2.编写 herodetailcomponent的模版(hero-detail.component.html)

从 heroescomponent 模板的底部把表示英雄详情的 html 代码剪切粘贴到所生成的 herodetailcomponent 模板中。

粘贴过来的html代码中,有selecthero这个属性,由于现在我们展示的不仅仅是被选中的hero,而是需要展示的是每一个hero,这个过程相当于将herodetail这个组件的功能扩大化。所以将其更改为: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>

因为herodetail重的hero是从其他父组件得到。所以hero 属性必须是一个带有 @input() 装饰器的输入属性,因为外部的 heroescomponent 组件将会绑定到它。

具体步骤:

导入hero

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

导入input符号

import { component, oninit, input } from '@angular/core';

定义hero

@input() hero: hero;

这样,就对herodetail的类文件写好了,herodetail所做的工作就是:从其他的父组件中接收一个hero类型的对象,并将它展示出来

3.显示 herodetailcomponent

现在有herodetail组件显示每一个hero的具体详情信息,而heroes组件需要显示每一个hero的详细信息,这个时候,heroes组件和herodetail组件就有了主从关系,heroes组件需要将需要展示详情的hero对象传给具有展示功能的herodetail组件

herodetailcomponent 的选择器是 'app-hero-detail'。 把 <app-hero-detail> 添加到 heroescomponent 模板的底部,以便把英雄详情的视图显示到那里,并把 heroescomponent.selectedhero 绑定到该元素的 hero 属性, heroescomponent模版即:

<h2>my heroes</h2>
<ul class="heroes">
 <li *ngfor="let hero of heroes" (click)="onselect(hero)" [class.selected]="hero === selectedhero">
  <span class="badge">{{hero.id}}</span> {{hero.name}}
 </li>
</ul>
<app-hero-detail [hero]="selectedhero"></app-hero-detail>

保存浏览器刷新,界面和之前的不会有变化,但是会有一下优点:

  • 通过缩减 heroescomponent 的职责简化了该组件。
  • 把 herodetailcomponent 改进成一个功能丰富的英雄编辑器,而不用改动父组件 heroescomponent。
  • 改进 heroescomponent,而不用改动英雄详情视图。
  • 将来可以在其它组件的模板中重复使用 herodetailcomponent。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。