File

src/lib/components/discuss-start/discuss-start.component.ts

Implements

OnInit

Metadata

Index

Properties
Methods
Inputs
Outputs

Constructor

constructor(discussService: DiscussionService, formBuilder: UntypedFormBuilder, telemetryUtils: TelemetryUtilsService, configService: ConfigService, discussUtils: DiscussUtilsService)
Parameters :
Name Type Optional
discussService DiscussionService No
formBuilder UntypedFormBuilder No
telemetryUtils TelemetryUtilsService No
configService ConfigService No
discussUtils DiscussUtilsService No

Inputs

categoryId
Type : string
mode
Type : string
topicData
Type : any

Outputs

close
Type : EventEmitter

Methods

closeModal
closeModal(eventMessage: string)
Parameters :
Name Type Optional
eventMessage string No
Returns : void
initializeData
initializeData()
Returns : void
initializeFormFields
initializeFormFields(topicData)
Parameters :
Name Optional
topicData No
Returns : void
isFieldValid
isFieldValid(field)
Parameters :
Name Optional
field No
Returns : any
logTelemetry
logTelemetry(event)
Parameters :
Name Optional
event No
Returns : void
ngOnInit
ngOnInit()
Returns : void
showError
showError(meta: string)
Parameters :
Name Type Optional
meta string No
Returns : boolean
Public submitPost
submitPost(form: any)
Parameters :
Name Type Optional
form any No
Returns : void
updatePost
updatePost(form: any)
           Here, as 'tid', we are passing the main topic pid from the post array
Parameters :
Name Type Optional
form any No
Returns : void
validateForm
validateForm()
Returns : void

Properties

allCategories
Type : NSDiscussData.ICategorie[]
allTags
Type : NSDiscussData.ITag[]
cIds
Type : any
createErrorMsg
Type : string
Default value : ''
defaultError
Type : string
Default value : 'Something went wrong, Please try again after sometime!'
editable
Default value : true
enableSubmitButton
Default value : false
postTagsArray
Type : string[]
Default value : []
showErrorMsg
Default value : false
showSelectCategory
Default value : false
startForm
Type : UntypedFormGroup
uploadSaveData
Default value : false
import { UntypedFormGroup, UntypedFormBuilder, Validators } from '@angular/forms';
import { DiscussionService } from './../../services/discussion.service';
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { NSDiscussData } from './../../models/discuss.model';
import { TelemetryUtilsService } from './../../telemetry-utils.service';
import { DiscussUtilsService } from '../../services/discuss-utils.service';
/* tslint:disable */
import * as _ from 'lodash'
import { ConfigService } from '../../services/config.service';
/* tslint:enable */

@Component({
  selector: 'lib-discuss-start',
  templateUrl: './discuss-start.component.html',
  styleUrls: ['./discuss-start.component.scss']
})
export class DiscussStartComponent implements OnInit {
  @Input() categoryId: string;
  @Input() topicData: any;
  @Input() mode: string;
  @Output() close = new EventEmitter();

  startForm!: UntypedFormGroup;
  editable = true;
  allCategories!: NSDiscussData.ICategorie[];
  allTags!: NSDiscussData.ITag[];
  postTagsArray: string[] = [];
  uploadSaveData = false;
  showErrorMsg = false;
  showSelectCategory = false;
  createErrorMsg = '';
  defaultError = 'Something went wrong, Please try again after sometime!';

  enableSubmitButton = false;
  cIds: any;

  constructor(
    private discussService: DiscussionService,
    private formBuilder: UntypedFormBuilder,
    private telemetryUtils: TelemetryUtilsService,
    private configService: ConfigService,
    private discussUtils: DiscussUtilsService
  ) { }

  ngOnInit() {
    (document.querySelector('[tabindex="-1"]') as HTMLElement).focus();
    // debugger
    this.telemetryUtils.logImpression(NSDiscussData.IPageName.START);
    this.cIds = this.configService.getCategories()
    if (this.categoryId) {
      this.showSelectCategory = false;
    } else {
    this.showSelectCategory = true;
    }

    this.initializeData();
    this.initializeFormFields(this.topicData);
  }

  initializeFormFields(topicData) {
    this.startForm = this.formBuilder.group({
      question: [null, [Validators.required, Validators.minLength(8)]],
      description: [null, [Validators.required, Validators.minLength(8)]],
      tags: [],
      category: []
    });
    this.startForm.valueChanges.subscribe(val => {
      this.validateForm();
    });

    /** If popup is in edit mode */
    if (topicData) {
      const tags = _.map(_.get(topicData, 'tags'), (element) => {
        return _.get(element, 'value');
      });

      /** calling htmlDecode method to get the parsed string */
      this.startForm.controls['question'].setValue(this.discussUtils.htmlDecode(_.get(topicData, 'title')));
      this.startForm.controls['description'].setValue(_.get(topicData, 'posts[0].content').replace(/<[^>]+>/g, ''));
      this.startForm.controls['tags'].setValue(tags);
      this.validateForm();
    }
  }

  isFieldValid(field) {
    let valueNoWhiteSpace = this.startForm.get(field).value;
    if (valueNoWhiteSpace) {
      const index = valueNoWhiteSpace.length;
      if (index >= 2 && valueNoWhiteSpace.charAt(index - 2) === " ") {
        this.startForm.patchValue({ replyContent: this.startForm.get(field).value.trim() });
      } else {
        this.startForm.patchValue({ replyContent: this.startForm.get(field).value.trimStart() })
      }
    }
    return (!this.startForm.get(field).valid && this.startForm.get(field).dirty);
  }

  validateForm() {
    if (this.startForm.status === 'VALID') {
      this.enableSubmitButton = true;
    } else {
      this.enableSubmitButton = false;
    }
  }

  initializeData() {
    // debugger
    if (this.configService.hasContext() && !this.categoryId) {
      const req = {
        cids: this.cIds.result
      };

      this.discussService.getContextBasedDiscussion(req).subscribe((data: any) => {
        this.allCategories = data.result;
        if (this.startForm.get('category')) { }
        this.startForm.controls['category'].setValue(this.allCategories[0].cid)
      });
    } else if (this.categoryId) {
      const req = {
        cids: [this.categoryId]
      };
      this.showSelectCategory = false;
      this.editable = false;
      this.discussService.getContextBasedDiscussion(req).subscribe((data: any) => {
        this.allCategories = data.result;
        if (this.startForm.get('category')) { }
        this.startForm.controls.category.setValue(this.allCategories[0].cid);
      });
    } else {
      this.discussService.fetchAllCategories().subscribe((data: any) => {
        this.allCategories = data
        if (this.startForm.get('category')) { }
        this.startForm.controls['category'].setValue(this.allCategories[1].cid)
      });
    }

    this.discussService.fetchAllTag().subscribe(data => {
      const tags = _.get(data, 'tags');
      this.allTags = _.map(tags, (tag) => tag.value);
    });
  }
  showError(meta: string) {
    if (meta) {
      return true;
    }
    return false;
  }

  public submitPost(form: any) {
    this.uploadSaveData = true;
    this.showErrorMsg = false;
    const postCreateReq = {
      cid: this.categoryId ? this.categoryId : parseInt(form.value.category),
      title: form.value.question,
      content: form.value.description,
      tags: form.value.tags,
    };
    this.discussService.createPost(postCreateReq).subscribe(
      () => {
        this.closeModal('success');
        form.reset();
        this.uploadSaveData = false;
        // success toast;
        // this.openSnackbar(this.toastSuccess.nativeElement.value)
        // close the modal
      },
      err => {
        this.closeModal('discard');
        // error toast
        // .openSnackbar(this.toastError.nativeElement.value)
        this.uploadSaveData = false;
        if (err) {
          if (err.error && err.error.message) {
            this.showErrorMsg = true;
            this.createErrorMsg = err.error.message.split('|')[1] || this.defaultError;
          }
        }
      });
  }


  /**
   * @param  {any} form
   * @description - It will emit an event when popup is opened in edit topic/thread mode
   *                Here, as 'tid', we are passing the main topic pid from the post array
   */
  updatePost(form: any) {
    const updateTopicRequest = {
      title: form.value.question,
      content: form.value.description,
      tags: form.value.tags,
      uid: _.get(this.topicData, 'uid')
    };
    this.close.emit({
      action: 'update',
      tid: _.get(this.topicData, 'posts[0].pid'),
      request: updateTopicRequest
    });
  }

  closeModal(eventMessage: string) {
    this.close.emit({ message: eventMessage });
  }

  logTelemetry(event) {
    this.telemetryUtils.logInteract(event, NSDiscussData.IPageName.START);
  }
}

<!--modals-->
<div class="modal fade" id="myModal">
  <div class="discussion-start-modal">
    <div class="discussion-start-modal-content" id="topic-scroll" tabindex="-1" role="dialog">
      <form [formGroup]="startForm" class="discussion-start-form">

        <div class="start-form-content" *ngIf="showSelectCategory" [ngClass]="{ 'is-invalid': showError('subTitle') }">
          <label class="start-form-label">Select category*</label>
          <div class="start-form-field">
            <label class="start-form-label" for="myList">Select list </label>
            <select formControlName="category" #category [required]="true" id="myList" class="select-category">
              <option [value]="c.cid" *ngFor="let c of allCategories" [innerHTML]="c.name"></option>
            </select>
          </div>
          <small class="mandatory-label" *ngIf="!startForm.get('category').valid" i18n="category Error|Explains category is required">
            category is mandatory</small>
        </div>

        <div class="start-form-content" [ngClass]="{ 'is-invalid': showError('subTitle') }">
          <label class="start-form-label">Discussion topic*</label>
          <div class="start-form-field">
            <input [ngClass]="{'is-invalid' : isFieldValid('question')}" class="start-form-field-control" placeholder="Type here (minimum 8 characters)"
              formControlName="question" #question maxlength="1000" />
          </div>
          <small class="mandatory-label" *ngIf="!startForm.get('question').valid" i18n="question Error|Explains question is required">
            Question is mandatory. It should be minimum of
            8 characters</small>
        </div>

        <div class="start-form-content">
          <div class="start-form-field">
            <label class="start-form-label" for="description">Please elaborate your question or idea here*</label>
            <textarea [ngClass]="{'is-invalid' : isFieldValid('description')}" minlength="8" class="start-form-field-control" rows="8" formControlName="description"
              #description name="moretext" placeholder="Type here (minimum 8 characters)" id="description"></textarea>
          </div>
          <small class="mandatory-label" *ngIf="!startForm.get('description').valid"
            i18n="description Error|Explains description is required"> Description is mandatory. It should be minimum of
            8 characters </small>
        </div>

        <div #postTags [ngClass]="{ 'is-invalid': showError('tags') }" class="start-tags">
          <label class="mb-0">Tags</label>
          <div *ngFor="let tag of postTagsArray">
            {{ tag }}
          </div>
          <!-- TODO: check the padding for placeholder -->
          <tag-input class="tag-input" secondaryPlaceholder="Add a tag and press Enter" formControlName="tags"
            [modelAsStrings]="true">
          </tag-input>
        </div>

        <div *ngIf="showErrorMsg">
          <small class="mandatory-label">
            {{createErrorMsg}}
          </small>
        </div>

        <div class="start-modal-buttons">
          <button (click)="closeModal('discard');logTelemetry($event)" mat-raised-button type="button"
            class="df-btn df-btn-normal df-cancel-btn" id="discard-discussion-start-form">Cancel
          </button>
          <span *ngIf="uploadSaveData">
          </span>
          <button *ngIf="mode !== 'edit'" type="submit" class="df-btn df-btn-normal df-btn-primary df-submit-btn"
            [ngClass]="{'df-btn-disabled': !enableSubmitButton }" [disabled]="!enableSubmitButton"
            (click)="submitPost(startForm);logTelemetry($event)" id="submit-discussion-start-form">
            <span class="text-white">Submit</span>
          </button>
          <button *ngIf="mode === 'edit'" type="submit" class="df-btn df-btn-normal df-btn-primary df-update-btn"
            [ngClass]="{'df-btn-disabled': !enableSubmitButton }" [disabled]="!enableSubmitButton"
            (click)="updatePost(startForm);logTelemetry($event)" id="update-topic-popup">
            <span class="text-white">Update</span>
          </button>
        </div>
        ​
      </form>
      ​
      <input type="hidden" i18-value i18-aria-value aria-value="Post created successful"
        value="Post created successfully!" #toastSuccess />
      <input type="hidden" i18-value i18-aria-value aria-value="unable to create post"
        value="Error in creating new post!" #toastError />
    </div>
  </div>
</div>

./discuss-start.component.scss

::ng-deep:root {
  --df-modal-content-bg: var(--df-common-bg);
  --df-modal-field-control-bg: var(--df-background);
  --df-tag-bg:var(--df-e9e8d9);
  --df-ng-tag-bg: var(--df-background);
}

#myModal{
  display: block;
  opacity: 2!important;
}

.discussion-start-modal {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background: rgba(0,0,0,.8);
  z-index: 99999;
  opacity: 1;
  transition: opacity .1s ease-in;
  pointer-events: auto;

  .discussion-start-modal-content {
    max-width: 50rem;
    width: 90%;
    position: relative;
    margin: 0 auto;
    padding: 1rem;
    border-radius: 0.1875rem;
    background: var(--df-modal-content-bg);
    color: var(--df-text);
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    overflow: auto;
    max-height: calc(100% - 156px);

    .discussion-start-form {
      .start-form-content {
        margin-bottom: 0.5rem;
      }

      .start-form-label {
        display: inline-block;
        margin-bottom: 0.5rem;
        font-size: 0.8125rem;
        font-weight: 700;
      }

      .start-form-field {
        position: relative;
        margin-bottom: 0;

        .select-category {
          border: 0.0625rem solid var(--gray-200);
          color: var(--df-text);
          margin: 0 0.5rem;
          padding: 0.5rem 0.25rem;
          background: var(--df-field-control-bg);
        }

        .start-form-field-control {
          background-color: var(--df-modal-field-control-bg);
          border: 0.0625rem solid var(--gray-200);
          border-radius: 0.1875rem;
          color: var(--df-text);
          display: block;
          font-size: 0.8125rem;
          font-family: sans-serif;
          position: relative;
          width: 96%;
          cursor: pointer;
          outline: none;
          padding: 0.5rem 0.875rem;
          &:focus,
          .active {
            border-color: var(--primary-400) !important;
          }
        }
      }

      .mandatory-label {
        font-size: 0.75rem;
        color: var(--red-100);
      }

      .start-modal-buttons {
        float: right;

        .df-submit-btn,
        .df-update-btn {
          margin-left: 0.5rem;
        }

        .df-cancel-btn {
          box-shadow: 0 2px 1px -1px rgba(0, 0, 0, .2), 0 1px 1px 0 rgba(0, 0, 0, .14), 0 1px 3px 0 rgba(0, 0, 0, .12);
          border:0;
          margin: 0 0.5rem;
        }

        .df-btn-disabled {
          background-color: var(--gray-100);
        }
      }

      .start-tags {
        margin-bottom: 1.5rem;

        label {
          display: inline-block;
          font-size: 0.8125rem;
          font-weight: 700;
          margin-bottom: 0;
        }
      }
    }
  }
}

#myModal {
  display: block;
  opacity: 2 !important;
}

::ng-deep {
  .ng2-tag-input {
    border: .0625rem solid var(--gray-200) !important;
    border-radius: 0.1875rem;
    color: var(--df-text) !important;
    display: block;
    font-size: 0.8125rem !important;
    max-width: 100%;
    padding: 0.25rem 0.5rem;
    margin: 0.5rem 0;
    background: var(--df-field-control-bg);
    border-radius: 0.1875rem;
    border-bottom: .0625rem solid var(--gray-200) !important;
  }

  .ng2-tag-input--focused {
    border-color: var(--primary-400) !important;
  }

  .ng2-tag-input__text-input {
    height: 2.25rem;
    margin: 0 0.5rem;
    color: var(--df-text);
    background: var(--df-ng-tag-bg);
  }

  .ng2-tag-input.active {
    border-color: var(--primary-400) !important;
  }

   tag {
    background: var(--df-tag-bg) !important;
    color: var(--df-text) !important;
    &:first-child{
      margin-left: 0.5rem !important;
    }
  }
}
Legend
Html element
Component
Html element with directive

results matching ""

    No results matching ""