新增业务组件

对于一些可能被多处引用的功能模块,建议提炼成业务组件统一管理。这些组件一般有以下特征:

  • 只负责一块相对独立,稳定的功能;

  • 没有单独的路由配置;

  • 可能是纯静态的,仅受父组件(通常是一个页面)传递的参数控制。

下面以一个简单的静态组件为例进行介绍。假设你的应用中经常需要展现图片,这些图片宽度固定,有一个灰色的背景和一定的内边距,有文字介绍,就像下图这样:

新增业务组件 - 图1

你可以用一个组件来实现这一功能,它有默认的样式,同时可以接收父组件传递的参数进行展示。

新建文件

src/app/shared/components 下新建一个以组件名命名的文件夹,命名尽量体现组件的功能,这里就叫 image-wrapper。在此文件夹下新增 ts 文件、样式文件(如果需要)及组件API说明,命名为 index.tsindex.lessREADME.md

在使用组件时,默认会在 index.ts 中寻找 export 的对象,如果你的组件比较复杂,可以分为多个文件,最后在 index.ts 中统一 export,就像这样:

  1. // main.component.ts
  2. export class MainComponent {}
  3. // sub.component.ts
  4. export class SubComponent {}
  5. // index.ts
  6. export MainComponent from './main.component';
  7. export SubComponent from './sub.component';

你的代码大概是这个样子:

  1. // index.ts
  2. import { Component, Input } from '@angular/core';
  3. @Component({
  4. selector: 'image-wrapper',
  5. template: `
  6. <div [ngStyle]="style">
  7. <img class="img" [src]="src" [alt]="desc" />
  8. <div *ngIf="desc" class="desc">{{ desc }}</div>
  9. </div>
  10. `,
  11. styleUrls: [ './index.less' ]
  12. })
  13. export class ImageWrapperComponent {
  14. @Input() style: { [key: string]: string };
  15. @Input() src: string;
  16. @Input() desc: string;
  17. }
  1. // index.less
  2. :host {
  3. width: 400px;
  4. margin: 0 auto;
  5. padding: 0 20px 8px;
  6. text-align: center;
  7. background: #f2f4f5;
  8. ::ng-deep {
  9. .img {
  10. max-width: calc(100% - 32px);
  11. margin: 2.4em 1em;
  12. vertical-align: middle;
  13. box-shadow: 0 8px 20px rgba(143, 168, 191, 0.35);
  14. }
  15. }
  16. }

到这儿组件就建好了,了解更多关于组件样式的开发。

注册

组件创建好后,需要将组件导入 SharedModule 中,这样所有子模块都可以使用到该组件。

  1. // shared.module.ts
  2. import { ImageWrapperComponent } from './image-wrapper';
  3. const COMPONENTS = [
  4. ImageWrapperComponent
  5. ];

使用

在要使用这个组件的地方,按照组件定义的 API 传入参数,直接使用就好:

  1. <image-wrapper
  2. src="https://os.alipayobjects.com/rmsportal/mgesTPFxodmIwpi.png"
  3. desc="示意图"></image-wrapper>