组件开发

组件继承关系

  1. IMaterialComp
  2. |-IBtnComp
  3. |-IFormComp

目录结构

  1. // 简单组件
  2. input
  3. |-input.type.ts
  4. |-input.interface.ts
  5. |-input.component.ts
  6. |-input.component.html
  7. |-input.component.scss
  8. |-index.ts
  9. // 复杂组件
  10. table
  11. |-animation
  12. |-option
  13. |-state
  14. |-comp
  15. |-index.ts

注解格式

  1. // ok
  2. @Input()
  3. placeholder: string;
  4. // err
  5. @Input() type: InputType;

公有属性放在class最前面

  1. export class InputComponent {
  2. @Input()
  3. placeholder: string;
  4. @Input()
  5. type: InputType;
  6. @Input()
  7. min: number;
  8. @Input()
  9. max: number;
  10. // internal
  11. _InputType = InputType;
  12. }

双向绑定

  1. // two-way binding
  2. private _value: string;
  3. @Output() valueChange = new EventEmitter();
  4. @Input() get value() {
  5. return this._value;
  6. }
  7. set value(_value) {
  8. if (_value !== this) {
  9. this._value = _value;
  10. this.valueChange.emit(_value);
  11. }
  12. }

类型定义

  1. export type ColorType = 'primary' | 'accent' | 'warn' | undefined;

import 格式

先后顺序(作用域)

  1. npm库在前面

  2. 范围最大的在前面

  3. 更外层的在前面

  1. // e.g.
  2. import {
  3. IFormComp,
  4. } from '../form.interface';
  5. import {
  6. InputType
  7. } from './input.type';
  1. {}中的变量按照字母顺序排列
  1. // e.g.
  2. import {
  3. InputType
  4. } from './input.type';
  5. import {
  6. // 字母顺序排列
  7. IInputComp,
  8. IInputOption,
  9. } from './input.interface';

class 格式

  1. 被依赖项写在依赖项之前

  2. 方法之间空1行

  3. 注解与class之间没有空行

  1. @Component({
  2. selector: 'mat-edit',
  3. templateUrl: './edit.component.html',
  4. styleUrls: [ './edit.component.scss'],
  5. })
  6. export class EditComponent implements OnInit, IEditComp {
  1. private属性和方法都加上_

class命名

统一前缀component-mat

  1. <div class="component-mat-upload__image-container">
  2. <div class="component-mat-upload__image-image-container" *ngFor="let image of images index as i">
  3. <img class="component-mat-upload__image-image" src="{{ image }}" alt="" />
  4. <mat-icon class="component-mat-upload__image-image-remove" (click)="onClickRemove(i)">close</mat-icon>
  5. </div>
  6. <div *ngIf="showUploadBtn" class="component-mat-upload__image-image-container component-mat-upload__image-button" (click)="uploadFile()">
  7. <mat-icon class="component-mat-upload__image-button-icon">add</mat-icon>
  8. <input
  9. #file1
  10. ng2FileSelect
  11. type="file"
  12. [(ngModel)]="value"
  13. [style.display]="'none'"
  14. [uploader]="uploader"
  15. (change)="selectedFileOnChanged($event)"
  16. />
  17. </div>
  18. </div>

样式

  1. 组件内部container不设置marginpadding

  2. margin, padding 方向,自左向右,自上而下,特殊情况特殊处理。