2.4.模板代码-更新

工具类

src/app/utils/form.util.ts

import {FormGroup} from '@angular/forms';

import {Injectable} from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class FormUtil {

  isValidForm(validateForm: FormGroup): boolean {
    if (validateForm.status !== 'VALID') {
      return false;
    }
    return true;
  }

  getFormData<T>(rawData: T, validateForm: FormGroup): T {
    for (let key in validateForm.controls) {
      validateForm.controls[key].markAsDirty();
      rawData[key] = validateForm.controls[key].value;
    }
    return rawData;
  }

}

Service

src/app/plan/plan.service.ts

import {Injectable} from '@angular/core';
import {Observable} from 'rxjs';
import {HttpClient, HttpHeaders} from '@angular/common/http';
import {Plan} from '../../domain/plan';


const httpOptions = {
  headers: new HttpHeaders({'Content-Type': 'application/json'})
};


@Injectable({
  providedIn: 'root'
})
export class PlanService {

  constructor(private http: HttpClient) {
  }

  /**
   * 更新计划
   *
   * @param id 计划的id
   * @param plan 计划
   * @return 计划
   */
  updatePlan(id: string, plan: Plan): Observable<Plan> {
    const url = '/mo/v1/plan/' + id;
    return this.http.put<Plan>(url, JSON.stringify(plan), httpOptions);
  }

}

父组件部分

模板

src/app/plan/plan.component.html

<a (click)="createEditModal(data)">更新</a>

控制器

src/app/plan/plan.component.ts

import {Component, OnInit, ViewContainerRef} from '@angular/core';
import {NzModalService} from 'ng-zorro-antd/modal';
import {NzMessageService} from 'ng-zorro-antd';

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

  constructor(private service: PlanService,
              private modal: NzModalService,
              private message: NzMessageService,
              private viewContainerRef: ViewContainerRef) {
  }


  /**
   * 创建编辑对话框
   */
  createEditModal(plan: any): void {

    const modal = this.modal.create({
      nzTitle: '编辑计划',
      // 对话框的内容,本例中为一个表单组件
      nzContent: PlanUpdateComponent,
      nzViewContainerRef: this.viewContainerRef,
      // 父组件传递给对话框的数据
      nzComponentParams: {
        data: plan,
      },
      nzOnOk: (componentInstance: PlanUpdateComponent) => {
        // 校验表单的正确性,若表单校验通过,则获取表单数据并调用api执行更新操作;否则返回false,不允许提交表单
        const isValid: boolean = componentInstance.isValidForm();
        if (isValid) {
          const result: Plan = componentInstance.getFormData();
          this.updatePlan(result.id, result);
          return result;
        }
        return false;
      }
    });
    // 当对话框开启时,打印日志
    modal.afterOpen.subscribe(() => console.log('[afterOpen] emitted!'));
    // 当对话框关闭时,返回结果
    modal.afterClose.subscribe(result => console.log('[afterClose] The result is:', result));
  }

  /**
   * 调用后台api更新计划
   * @param id 计划id
   * @param updateData 更新数据
   */
  updatePlan(id: string, updateData: Plan): void {
    const messageId = this.message.loading('正在更新中...', {nzDuration: 0}).messageId;
    this.service.updatePlan(id, updateData).subscribe(
      // 若调用api成功,打印api返回值,提示创建更新成功,并刷新列表
      (data) => {
        console.log('next: ' + data);
        this.message.remove(messageId);
        this.message.success('更新成功!');
        this.refreshData();
      },
      // 若调用api失败,打印失败日志,提示更新失败
      (error) => {
        console.log('error: ' + error);
        this.message.error('更新失败!');
        this.message.remove(messageId);
      }
    );
  }

  /**
   * 刷新数据
   */
  refreshData(): void {
    this.listPlans();
  }

}

对话框部分

模板

src/app/plan/plan-update/plan-update.component.html

<form nz-form [formGroup]="validateForm">

  <nz-form-item>
    <nz-form-label [nzSm]="6" [nzXs]="24" nzFor="name" nzRequired>name</nz-form-label>
    <nz-form-control [nzSm]="14" [nzXs]="24" nzErrorTip="The input is not valid name!">
      <input nz-input id="name" formControlName="name"/>
    </nz-form-control>
  </nz-form-item>

    ...

</form>

控制器

src/app/plan/plan-update/plan-update.component.ts

import {Component, Input, OnInit} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {FormUtil} from '../../../utils/form.util';
import {NzModalRef} from 'ng-zorro-antd';

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

  // 对话框需要的参数,由外部组件传入
  @Input() data?: Plan;

  validateForm!: FormGroup;

  constructor(
    private fb: FormBuilder
    private formUtil: FormUtil,
    private modal: NzModalRef
  ) {
  }

  ngOnInit(): void {
    // 初始化表单
    this.validateForm = this.fb.group({
      name: [this.data.name, [Validators.required]],
      expectedValue: [this.data.expectedValue, [Validators.required]],
      rangePicker: [[this.data.startTime, this.data.expireTime]],
      description: [this.data.description, [Validators.required]],
    });
  }

  /**
   * 校验表单
   */
  isValidForm(): boolean {
    return this.formUtil.isValidForm(this.validateForm);
  }

  /**
   * 获取表单数据并进行处理
   */
  getFormData(): Plan {
    const data: Plan = this.formUtil.getFormData(this.data, this.validateForm);
    const times: any[] = this.validateForm.get('rangePicker').value;
    data.startTime = times[0];
    data.expireTime = times[1];
    return data;
  }

}

Last updated

Was this helpful?