Angular функциональности> Кнопки редактирования и вверх и вниз - PullRequest
0 голосов
/ 21 апреля 2020

Я работаю с Angular на CMS, которая редактирует схемы, и у меня есть много функций, которые можно добавить на страницу. Есть кнопка удаления, кнопка редактирования и 2 другие кнопки, вверх и вниз, для перемещения каждой строки.
1. Кнопка удаления = нормально
2. Кнопка редактирования = она работает, но в режиме редактирования, я бы нравится менять значок редактирования на значок подтверждения
3. Кнопки вверх и вниз = я пробовал много вещей, но это не работает. У кого-нибудь есть идея?

Код ниже. Скажите, если вам нужно больше
Спасибо =]

BaseType.ts

export enum BaseType {
  STRING = "STRING",
  FLOAT = "FLOAT",
  INTEGER = "INTEGER",
  BOOLEAN = "BOOLEAN"
}

ConstraintType.ts

export enum ConstraintType {
  UNIQUE = "UNIQUE",
  NOT_NULL = "NOT_NULL",
  MIN_LENGTH = "MIN_LENGTH",
  MAX_LENGTH = "MAX_LENGTH"
}

attribute-Dynami c -form .component.ts

import { Component, EventEmitter, Input, OnInit, Output } from "@angular/core";
import { FormArray, FormControl, FormGroup } from "@angular/forms";
import { BaseType } from "src/app/shared/models/BaseType";
import { ConstraintType } from "src/app/shared/models/ConstraintType";

interface Attribute {
  id: number;
  name: string;
  type: string;
  constraint: string;
}

interface Name {
  value: string;
}
interface Type {
  value: string;
}

interface Constraint {
  value: string;
}

@Component({
  selector: "app-attributes-dynamic-form",
  templateUrl: "./attributes-dynamic-form.component.html",
  styleUrls: ["./attributes-dynamic-form.component.scss"]
})
export class AttributesDynamicFormComponent implements OnInit {
  attribute: Attribute = {
    id: 1,
    name: "name",
    type: "type",
    constraint: "constraint"
  };

  names: { value: "name" };
  types: { value: BaseType }[];
  constraints: { value: ConstraintType }[];

  editableChgeEmit: EventEmitter<void>;
  formGroup: FormGroup;

  ngOnInit() {
    this.editableChgeEmit = new EventEmitter();

    this.formGroup = new FormGroup({
      name: new FormControl(this.attribute.name),
      type: new FormControl(this.attribute.type),
      constraint: new FormControl(this.attribute.constraint)
    });

    this.types = Object.keys(BaseType).map(baseType => ({
      value: baseType as BaseType
    }));

    this.constraints = Object.keys(ConstraintType).map(constraintType => ({
      value: constraintType as ConstraintType
    }));
  }

  getControl(field: string): FormControl {
    return this.formGroup.get(field) as FormControl;
  }

  typeKeyToDisplay(key: string) {
    const type = this.types.find(t => t.value === key);
    return type.value;
  }

  constraintKeyToDisplay(key: string) {
    const constraint = this.constraints.find(c => c.value === key);
    return constraint.value;
  }

  updateField(field: string) {
    const control = this.getControl(field);
    this.attribute[field] = control.value;
  }

  // générer la liste des types de l'énumération BaseType
  // keysTypes = Object.keys(BaseType);

  // générer la liste des types de l'énumération Constraints
  // keysConstraints = Object.keys(ConstraintType);

  // row edit
  @Input() id: number;
  @Output() edit: EventEmitter<any> = new EventEmitter();
  onClickEdit() {
    // btn.active = !btn.active;
    this.editableChgeEmit.emit();
    // this.edit.emit(this.id);
  }

  // row up
  @Output() up: EventEmitter<any> = new EventEmitter();
  onClickUp() {}

  // row down
  @Output() down: EventEmitter<any> = new EventEmitter();
  onClickDown() {}

  // row delete
  @Output() delete: EventEmitter<any> = new EventEmitter();
  onClickDelete() {
    this.delete.emit(this.id);
  }
}

attribute-dynamici c -form.component. html

<div class="container">
  <div class="row">
    <div class="col-sm">
      <tbody>
        <table class="table">
          <tr class="form-group">

            <!-- row 01: Name -->
            <td class="field-attribute-name">
              <editable
                *ngIf="!!editableChgeEmit"
                [change]="editableChgeEmit"
                (update)="updateField('name')"
              >
                <ng-template viewMode>{{ attribute.name }}</ng-template>
                <ng-template editMode>
                  <input (keyup.enter)="onClickEdit()" [formControl]="getControl('name')" />
                </ng-template>
              </editable>
            </td>

            <!-- row 02: Types -->
            <td class="field-attribute-type">
              <editable
                *ngIf="!!editableChgeEmit"
                [change]="editableChgeEmit"
                (update)="updateField('type')"
              >
                <ng-template viewMode>{{ attribute.type }}</ng-template>
                <ng-template editMode
                  ><select [formControl]="getControl('type')">
                    <option
                      *ngFor="let type of types; let i = index"
                      [value]="type.value"
                    >
                      {{ type.value }}</option
                    >
                  </select>
                </ng-template>
              </editable>
            </td>

            <!-- row 03 : Constraints -->
            <td class="field-attribute-constraint">
              <editable
                *ngIf="!!editableChgeEmit"
                [change]="editableChgeEmit"
                (update)="updateField('constraint')"
              >
                <ng-template viewMode>{{ attribute.constraint }}</ng-template>
                <ng-template editMode
                  ><select [formControl]="getControl('constraint')">
                    <option
                      *ngFor="let constraint of constraints; let i = index"
                      [value]="constraint.value"
                    >
                      {{ constraint.value }}</option
                    >
                  </select>
                </ng-template>
              </editable>
            </td>

            <div class="buttons">
              <!-- edit button -->
              <app-mat-icon
                class="update-attribute-btn"
                [btnIcon]="'edit'"
                (click)="onClickEdit()"
              >
              </app-mat-icon>

              <!-- up button -->
              <app-mat-icon
                class="up-attribute-btn"
                [btnIcon]="'arrow_drop_up'"
                (click)="onClickUp()"
              >
              </app-mat-icon>

              <!-- down button -->
              <app-mat-icon
                class="down-attribute-btn"
                [btnIcon]="'arrow_drop_down'"
                (click)="onClickDown()"
              >
              </app-mat-icon>

              <!-- delete button -->
              <app-mat-icon
                class="delete-attribute-btn"
                [btnIcon]="'cancel'"
                (click)="onClickDelete()"
              >
              </app-mat-icon>
            </div>

          </tr>
        </table>
      </tbody>
    </div>
  </div>
</div>

edit-mode.directive.ts

import { Directive, TemplateRef } from "@angular/core";

@Directive({
  selector: "[editMode]"
})
export class EditModeDirective {
  constructor(public tpl: TemplateRef<any>) { }
}

view-mode.directive.ts

import { Directive, TemplateRef } from "@angular/core";

@Directive({
  selector: "[viewMode]"
})
export class ViewModeDirective {
  constructor(public tpl: TemplateRef<any>) { }
}

editable.component.ts

import {
  Component,
  ContentChild,
  ElementRef,
  EventEmitter,
  Output,
  Input
} from "@angular/core";
// import { NgControl } from "@angular/forms;";
import { Subject } from "rxjs";
import { EditModeDirective } from "./edit-mode.directive";
import { ViewModeDirective } from "./view-mode.directive";

@Component({
  selector: "editable",
  template: `
    <ng-container *ngTemplateOutlet="currentView"></ng-container>
  `,
  styleUrls: ["./editable.component.scss"]
})
export class EditableComponent {
  @ContentChild(ViewModeDirective, { static: false })
  viewModeTpl: ViewModeDirective;
  @ContentChild(EditModeDirective, { static: false })
  editModeTpl: EditModeDirective;
  @Output() update = new EventEmitter();

  @Input() change: EventEmitter<void>;

  mode: "view" | "edit" = "view";

  constructor(private host: ElementRef) {}

  ngOnInit() {
    console.log(this.change);
    this.change.subscribe(_ => {
      this.changeMode();
    });
  }

  changeMode() {
    if (this.mode === "view") {
      this.toEditMode();
    } else {
      this.toViewMode();
    }
  }

  toViewMode() {
    this.update.next();
    this.mode = "view";
  }

  toEditMode() {
    this.update.next();
    this.mode = "edit";
  }

  private get element() {
    return this.host.nativeElement;
  }

  get currentView() {
    return this.mode === "view" ? this.viewModeTpl.tpl : this.editModeTpl.tpl;
  }

  ngOnDestroy() {}
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...