File

src/app/pages/containers/configs-table/configs-table.component.ts

Implements

OnInit

Metadata

selector app-configs-table
styleUrls ./configs-table.component.scss
templateUrl ./configs-table.component.html

Index

Properties
Methods
Inputs
Outputs
Accessors

Constructor

constructor(route: ActivatedRoute, router: Router, fb: FormBuilder, _modalService: NgbModal)
Parameters :
Name Type Optional
route ActivatedRoute No
router Router No
fb FormBuilder No
_modalService NgbModal No

Inputs

configObject
global

Outputs

save
Type : EventEmitter

Methods

addConfig
addConfig()
Returns : void
getConfigFormValue
getConfigFormValue()
Returns : { config: {}; }
getConfigs
getConfigs()
Returns : void
Private Static getDismissReason
getDismissReason(reason: any)
Parameters :
Name Type Optional
reason any No
Returns : string
initialForm
initialForm()
Returns : FormGroup
initialize
initialize()
Returns : void
ngOnInit
ngOnInit()
Returns : void
onBlur
onBlur(event)
Parameters :
Name Optional
event No
Returns : void
onCancel
onCancel(content)
Parameters :
Name Optional
content No
Returns : void
onPublish
onPublish(content)
Parameters :
Name Optional
content No
Returns : void
onReset
onReset(content)
Parameters :
Name Optional
content No
Returns : void
open
open(content)
Parameters :
Name Optional
content No
Returns : void
remove
remove(index: number)
Parameters :
Name Type Optional
index number No
Returns : void

Properties

__
Default value : strings
configForm
Type : FormGroup
modalDescription
Type : any
Default value : "Modal Description"
modalHeader
Type : any
Default value : "Modal Header"
updateEnabled
Type : boolean
Default value : false

Accessors

getFormData
getgetFormData()
import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
import strings from '@i18n/strings.json';
import {FormArray, FormBuilder, FormGroup} from '@angular/forms';
import {ActivatedRoute, Router} from '@angular/router';
import {ModalDismissReasons, NgbModal} from "@ng-bootstrap/ng-bootstrap";

@Component({
  selector: 'app-configs-table',
  templateUrl: './configs-table.component.html',
  styleUrls: ['./configs-table.component.scss']
})
export class ConfigsTableComponent implements OnInit {

  __ = strings;
  @Input() global;
  @Input() configObject;
  @Output() save = new EventEmitter();
  configForm: FormGroup;
  updateEnabled: boolean = false;
  modalHeader: any = "Modal Header";
  modalDescription: any = "Modal Description";

  constructor(private route: ActivatedRoute,
              private router: Router,
              private fb: FormBuilder,
              private _modalService: NgbModal) {}

  ngOnInit() {
    this.initialize();
  }

  getConfigs() {
    const control = this.configForm.get('config') as FormArray;
    for (const c of this.configObject) {
      const grp = this.fb.group({
        name: [c.name],
        value: [c.value],
        scope: [c.scope],
        default: [c.default]
      });
      control.push(grp);
    }
  }

  initialForm(): FormGroup {
    return this.fb.group({
      name: [''],
      value: [''],
      scope: [''],
      default: ['']
    });
  }

  get getFormData(): FormArray {
    return this.configForm.get('config') as FormArray;
  }

  addConfig() {
    const control = this.configForm.get('config') as FormArray;
    control.push(this.initialForm());
  }

  remove(index: number) {
    const control = this.configForm.get('config') as FormArray;
    control.removeAt(index);
  }

  // onPublish() {
  //   this.save.emit(this.configForm.value);
  // }

  onPublish(content) {
    this.modalHeader = 'Publish configuration';
    this.modalDescription= {
      firstLine: `You are going to publish new configurations. Are you sure?`,
      secondLine: `All configuration will be overwritten permanently.`,
      thirdLine: `This operation cannot be undone.`
    };
    // this._modalService.open(NgbdModalConfirmAutofocus);
    // this.save.emit(this.configForm.value);

    this._modalService.open(content, {ariaLabelledBy: 'modal-basic-title'}).result.then((result) => {
      console.log(`Closed with: ${result}`);
      this.save.emit(this.configForm.value);
    }, (reason) => {
      console.log(`Dismissed ${ConfigsTableComponent.getDismissReason(reason)}`);
      // this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
    });
  }

  initialize() {
    this.configForm = this.fb.group({
      config: this.fb.array([])
    });
    this.getConfigs();
  }

  // onReset() {
  //   this.initialize();
  //   this.updateEnabled = false;
  // }

  onReset(content) {
    this.modalHeader = 'Reset configuration';
    this.modalDescription= {
      firstLine: `You are going to reset configurations. Are you sure?`,
      secondLine: `All configuration will be reset to previous one.`,
      thirdLine: `This operation cannot be undone.`
    };
    this._modalService.open(content, {ariaLabelledBy: 'modal-basic-title'}).result.then((result) => {
      console.log(`Closed with: ${result}`);
      this.initialize();
      this.updateEnabled = false;
    }, (reason) => {
      console.log(`Dismissed ${ConfigsTableComponent.getDismissReason(reason)}`);
      // this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
    });
    // this._modalService.open(NgbdModalConfirmAutofocus);
  }

  // onCancel() {
  //   const tempObject = {...this.route.snapshot.queryParams};
  //   delete tempObject.client;
  //   // TODO clients or global clients or users or groups?
  //   // console.log(this.global);
  //   if (this.global) {
  //     this.router.navigate(['/global-clients'], {queryParams: tempObject});
  //   } else {
  //     this.router.navigate(['/clients'], {queryParams: tempObject});
  //   }
  // }

  onCancel(content) {
    this.modalHeader = 'Cancel configuration';
    this.modalDescription= {
      firstLine: `You are going to cancel configurations. Are you sure?`,
      secondLine: `All configuration will not be saved.`,
      thirdLine: `This operation cannot be undone.`
    };
    this._modalService.open(content, {ariaLabelledBy: 'modal-basic-title'}).result.then((result) => {
      console.log(`Closed with: ${result}`);
      const tempObject = {...this.route.snapshot.queryParams};
      delete tempObject.client;
      // TODO clients or global clients or users or groups?
      // console.log(this.global);
      if (this.global) {
        this.router.navigate(['/global-clients'], {queryParams: tempObject});
      } else {
        this.router.navigate(['/clients'], {queryParams: tempObject});
      }
    }, (reason) => {
      console.log(`Dismissed ${ConfigsTableComponent.getDismissReason(reason)}`);
      // this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
    });
    // this._modalService.open(MODALS[name]);
  }
  
  // if change occurred save and reset activate
  // if change focus from input happens, check the change
  onBlur(event){
    const configValue = this.getConfigFormValue().config;
    // console.log(configValue);
    // if (this.updateEnabled === true) {return;}
    // console.log('onBlur',event);
    // console.log(this.configObject);
    // console.log(this.configForm.value.config);
    for (let i=0;i<configValue.length;i++){
      if(!this.configObject[i]) {this.updateEnabled = true; return;}
    //   // console.log(this.configObject[i].name != this.configForm.value.config[i].name);
    //   // console.log(this.configObject[i].value != this.configForm.value.config[i].value);
      if(this.configObject[i].name != configValue[i].name) {
        this.updateEnabled = true;
        return;
        // console.log('updateEnabled');
      }
      if(this.configObject[i].value != configValue[i].value) {
        this.updateEnabled = true;
        return;
        // console.log('updateEnabled');
      }
    }
    this.updateEnabled = false;
  }


  getConfigFormValue() {
    // console.log(this.configForm.value.config);
    let newConfigFormValue = [];
    for(let i=0;i<this.configForm.value.config.length;i++){
      if(this.configForm.value.config[i].name !== "" && this.configForm.value.config[i].value !== "" ){
        newConfigFormValue.push(this.configForm.value.config[i]);
      }
    }
    return {config: newConfigFormValue};

  }

  open(content) {
    this._modalService.open(content, {ariaLabelledBy: 'modal-basic-title'}).result.then((result) => {
      console.log(`Closed with: ${result}`);
      // this.closeResult = `Closed with: ${result}`;
    }, (reason) => {
      console.log(`Dismissed ${ConfigsTableComponent.getDismissReason(reason)}`);
      // this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
    });
  }

  private static getDismissReason(reason: any): string {
    if (reason === ModalDismissReasons.ESC) {
      return 'by pressing ESC';
    } else if (reason === ModalDismissReasons.BACKDROP_CLICK) {
      return 'by clicking on a backdrop';
    } else {
      return  `with: ${reason}`;
    }
  }
}
<div class="container-fluid">
  <div class="row">
  <div class="col-md-10 container-config">
    <form [formGroup]="configForm">
      <table class="table">
        <thead>
          <tr>
            <th scope="col">{{__.name}}</th>
            <th scope="col">{{__.value}}</th>
            <th scope="col">{{__.defaultValue}}</th>
            <th scope="col"></th>
          </tr>
        </thead>
        <tbody formArrayName="config" *ngFor="let group of getFormData.controls; let i=index">
          <tr [formGroupName]="i.toString()">
            <td class="form-group">
              <input
                type="text"
                class="form-control"
                formControlName="name"
                [placeholder]="__.name"
                aria-label="Name"
                [readonly]="group.value.default"
                [ngClass]="{'disabled' : group.value.default}"
                (blur)="onBlur($event)">
            </td>
            <td>
              <input
                type="text"
                class="form-control"
                formControlName="value"
                [placeholder]="__.value"
                aria-label="Value"
                (blur)="onBlur($event)">
            </td>
            <td style="width: 33%;">
              <p>{{group.value.default}}</p>
            </td>
            <td style="width: 16px;">
              <button (click)="remove(i)" class="btn btn-primary" [ngClass]="{'disabled' : group.value.default}" [disabled]="group.value.default">
                <mat-icon style="font-size: 16px;width: 16px; height:16px">delete</mat-icon>
              </button>
            </td>
          </tr>
        </tbody>
      </table>
    </form>
    <button mat-button (click)="addConfig()" class="btn btn-primary btn-block add-config"><mat-icon class="mr-1">
      add_circle</mat-icon>{{__.addANameValueConfiguration}}</button>
  </div>
  <div class="col-md-2 sidebar-config mt-5 mt-md-0">
    <button class="btn btn-primary btn-block" [ngClass]="{'disabled' : !updateEnabled}" [disabled]="!updateEnabled" (click)="onPublish(modalContent)">{{__.publish}}</button>
    <button class="btn btn-primary btn-block" [ngClass]="{'disabled' : !updateEnabled}" [disabled]="!updateEnabled" (click)="onReset(modalContent)">{{__.reset}}</button>
    <button class="btn btn-primary btn-block" (click)="onCancel(modalContent)">{{__.cancel}}</button>
  </div>
</div>
</div>

<ng-template #modalContent let-modal>
  <div class="modal-header">
    <h4 class="modal-title" id="modal-basic-title">{{modalHeader}}</h4>
    <button type="button" class="close" aria-label="Close" (click)="modal.dismiss('Cross click')">
      <span aria-hidden="true">&times;</span>
    </button>
  </div>
  <div class="modal-body">
    <p><strong>{{modalDescription.firstLine}}</strong></p>
    <p>{{modalDescription.secondLine}}
      <span class="text-danger">{{modalDescription.thirdLine}}</span>
    </p>
  </div>
  <div class="modal-footer">
    <button type="button" class="btn btn-outline-dark" (click)="modal.dismiss('Cancel click')">Cancel</button>
    <button type="button" class="btn btn-outline-dark" (click)="modal.close('Ok click')">OK</button>
  </div>
</ng-template>

./configs-table.component.scss

Legend
Html element
Component
Html element with directive

result-matching ""

    No results matching ""