quilljs copyCode module - Failed to execute 'insertBefore' on 'Node' - javascript

I am creating a copyCode plugin for QuillJs. Everything seems to be working for the plugin, however, when a space is created between the text and the code-block, you get this error:
Failed to execute 'insertBefore' on 'Node'
Here is the code:
const copyContentIntoClipboard = (rawData: string) => {
const encodedContent = encodeURIComponent(rawData);
const filteredEncodedContent = encodedContent.replace(/%EF%BB%BF/g, "");
const targetContent = decodeURIComponent(filteredEncodedContent);
const tmpHolder = document.createElement("textarea");
tmpHolder.value = targetContent;
document.body.appendChild(tmpHolder);
tmpHolder.select();
document.execCommand("copy");
document.body.removeChild(tmpHolder);
};
const CodeBlock = Quill.import("formats/code-block");
class CopyCode extends CodeBlock {
copyBadge: HTMLDivElement | null;
domNode: HTMLElement;
container: HTMLElement | null;
parent: HTMLElement;
copyHandler: EventListener;
_mountContainer() {
const container = document.createElement("div");
container.classList.add("ql-container");
if (this.domNode.nextSibling) {
this.domNode.parentElement?.insertBefore(
container,
this.domNode
);
container.appendChild(this.domNode); // <-- error starts here
this.container = container;
}
}
_dismountContainer() {
if (this.container) {
this.container.parentElement?.insertBefore(
this.domNode,
this.container.nextSibling
);
this.domNode.parentElement?.removeChild(this.container);
}
this.container = null;
}
_mountBadge() {
const copyBadge = document.createElement("div");
copyBadge.contentEditable = "false";
copyBadge.classList.add("ql-badge", "ql-badge-copy");
copyBadge.textContent = "copy";
this.domNode.parentElement?.insertBefore(
copyBadge,
this.domNode.nextSibling
);
const copyHandler = (e: MouseEvent) => {
e.stopPropagation();
e.preventDefault();
const target = e.target as HTMLElement;
const codeArea = target.previousSibling;
const copyCode = codeArea?.textContent?.trim() || '';
if (!codeArea) {
return;
}
copyBadge.textContent = "copied!";
setTimeout(function() {
copyBadge.textContent = "copy";
}, 2000);
copyContentIntoClipboard(copyCode);
};
copyBadge.addEventListener("click", copyHandler, true);
this.copyHandler = copyHandler;
this.copyBadge = copyBadge;
}
_dismountBadge() {
const badgeIsInDom = this.domNode.parentElement?.contains(this.copyBadge);
if (this.copyBadge && badgeIsInDom) {
this.copyBadge.removeEventListener("click", this.copyHandler, true);
this.copyBadge.parentElement?.removeChild(this.copyBadge);
}
this.copyBadge = null;
this.copyHandler = () => {};
}
_mount() {
this._mountContainer();
this._mountBadge();
}
insertInto(...args: any) {
super.insertInto(...args);
const allowCustomMount = !this.copyBadge && !this.container && this.parent;
if (allowCustomMount) {
this._mount();
}
}
remove() {
this._dismountBadge();
this._dismountContainer();
super.remove();
}
}
Here is the StackBlitz: https://stackblitz.com/edit/typescript-ggvuuy?file=index.html
I believe the error is caused by QuillJS believing the code-block should be a pre block instead of a div block containing a pre block. However, I don't know how to fix it...
Any ideas?

Instead of extending formats/code-block you can use Modules to extend Quill
import hljs from "highlight.js";
import "highlight.js/styles/monokai-sublime.css";
import "./style.css";
import Quill from "quill";
hljs.configure({
languages: ["javascript", "python"]
});
const copyContentIntoClipboard = (rawData: string) => {
const encodedContent = encodeURIComponent(rawData);
const filteredEncodedContent = encodedContent.replace(/%EF%BB%BF/g, "");
const targetContent = decodeURIComponent(filteredEncodedContent);
const tmpHolder = document.createElement("textarea");
tmpHolder.value = targetContent;
document.body.appendChild(tmpHolder);
tmpHolder.select();
document.execCommand("copy");
document.body.removeChild(tmpHolder);
};
class CopyCode {
quill: any;
options: any;
container: HTMLElement;
unusedBadges: HTMLElement[] = [];
reference: { [index: string]: {
parent : HTMLElement | null,
copyBadge : HTMLElement | null
} } = {};
constructor(quill: any, options: any) {
this.quill = quill;
this.options = options;
this.container = this.quill.addContainer('ql-badge-container');
this.quill.root.parentNode.style.position = this.quill.root.parentNode.style.position || 'relative';
this.registerCodeBlock();
this.quill.on('editor-change', () => {
Object.values(this.reference).forEach((item) => {
this.addCopyBadge(item);
this.repositionCopyBadge(item);
})
});
}
registerCodeBlock = () => {
const self = this;
const CodeBlock = Quill.import("formats/code-block");
let counter = 0;
class CopyMode extends CodeBlock {
domNode: HTMLElement;
insertInto(...args: any) {
super.insertInto(...args);
const index = String(counter);
const _node = this.domNode;
_node.setAttribute('data-index', index);
counter++;
self.reference[index] = { parent : _node, copyBadge: null };
}
remove() {
const index = this.domNode.getAttribute("data-index");
if (self.reference[index] && self.reference[index]['copyBadge']) {
const copyBadge = self.reference[index]['copyBadge'];
copyBadge.style.display = 'none';
self.unusedBadges.push(copyBadge);
}
delete self.reference[index];
super.remove();
}
}
Quill.register(CopyMode, true);
}
addCopyBadge = (obj: any) => {
if (obj.copyBadge != null || obj.parent == null) {
return;
}
const index = obj.parent.getAttribute('data-index');
const copyBadge = this.unusedBadges.length ? this.unusedBadges.shift() : document.createElement("span");
copyBadge.style.display = 'block';
copyBadge.contentEditable = "false";
copyBadge.classList.add("ql-badge", "ql-badge-copy");
copyBadge.textContent = "copy";
const copyHandler = (evt: MouseEvent) => {
evt.stopPropagation();
evt.preventDefault();
const codeArea = obj.parent;
const copyText = codeArea?.textContent?.trim() || '';
if (!codeArea) {
return;
}
copyBadge.textContent = "copied!";
setTimeout(function() {
copyBadge.textContent = "copy";
}, 2000);
copyContentIntoClipboard(copyText);
};
copyBadge.addEventListener("click", copyHandler, true);
this.container.appendChild(copyBadge);
this.reference[index]['copyBadge'] = copyBadge;
}
repositionCopyBadge(obj: any) {
const parent: HTMLElement = this.quill.root.parentNode;
const specRect = obj.parent.getBoundingClientRect();
const parentRect = parent.getBoundingClientRect();
Object.assign(obj.copyBadge.style, {
right: `${specRect.left - parentRect.left - 1 + parent.scrollLeft + 4}px`,
top: `${(specRect.top - parentRect.top + parent.scrollTop) + 3}px`,
});
}
}
Quill.register("modules/copy-code", CopyCode);
const quill = new Quill("#editor", {
modules: {
syntax: true,
'copy-code': true,
toolbar: {
container: ["code-block"]
}
},
theme: "snow"
});
Here working example

Related

Delete image read after running script

Good evening! I have a problem.
I am creating a collection of NFTs using this js file.
What I am trying to modify is that once it reads the images in the layers folder, creates the final image and writes the metadata, these read and used images are deleted in the source folder (${basePath}/layers).
const basePath = process.cwd();
const { NETWORK } = require(`${basePath}/constants/network.js`);
const fs = require("fs");
const sha1 = require(`${basePath}/node_modules/sha1`);
const { createCanvas, loadImage } = require(`${basePath}/node_modules/canvas`);
const buildDir = `${basePath}/build`;
const layersDir = `${basePath}/layers`;
const {
format,
baseUri,
description,
background,
uniqueDnaTorrance,
layerConfigurations,
rarityDelimiter,
shuffleLayerConfigurations,
debugLogs,
extraMetadata,
text,
namePrefix,
network,
solanaMetadata,
gif,
} = require(`${basePath}/src/config.js`);
const canvas = createCanvas(format.width, format.height);
const ctx = canvas.getContext("2d");
ctx.imageSmoothingEnabled = format.smoothing;
var metadataList = [];
var attributesList = [];
var dnaList = new Set();
const DNA_DELIMITER = "-";
const HashlipsGiffer = require(`${basePath}/modules/HashlipsGiffer.js`);
let hashlipsGiffer = null;
const buildSetup = () => {
if (fs.existsSync(buildDir)) {
fs.rmdirSync(buildDir, { recursive: true });
}
fs.mkdirSync(buildDir);
fs.mkdirSync(`${buildDir}/json`);
fs.mkdirSync(`${buildDir}/images`);
if (gif.export) {
fs.mkdirSync(`${buildDir}/gifs`);
}
};
const getRarityWeight = (_str) => {
let nameWithoutExtension = _str.slice(0, -4);
var nameWithoutWeight = Number(
nameWithoutExtension.split(rarityDelimiter).pop()
);
if (isNaN(nameWithoutWeight)) {
nameWithoutWeight = 1;
}
return nameWithoutWeight;
};
const cleanDna = (_str) => {
const withoutOptions = removeQueryStrings(_str);
var dna = Number(withoutOptions.split(":").shift());
return dna;
};
const cleanName = (_str) => {
let nameWithoutExtension = _str.slice(0, -4);
var nameWithoutWeight = nameWithoutExtension.split(rarityDelimiter).shift();
return nameWithoutWeight;
};
const getElements = (path) => {
return fs
.readdirSync(path)
.filter((item) => !/(^|\/)\.[^\/\.]/g.test(item))
.map((i, index) => {
return {
id: index,
name: cleanName(i),
filename: i,
path: `${path}${i}`,
weight: getRarityWeight(i),
};
});
};
const layersSetup = (layersOrder) => {
const layers = layersOrder.map((layerObj, index) => ({
id: index,
elements: getElements(`${layersDir}/${layerObj.name}/`),
name:
layerObj.options?.["displayName"] != undefined
? layerObj.options?.["displayName"]
: layerObj.name,
blend:
layerObj.options?.["blend"] != undefined
? layerObj.options?.["blend"]
: "source-over",
opacity:
layerObj.options?.["opacity"] != undefined
? layerObj.options?.["opacity"]
: 1,
bypassDNA:
layerObj.options?.["bypassDNA"] !== undefined
? layerObj.options?.["bypassDNA"]
: false,
}));
return layers;
};
const saveImage = (_editionCount) => {
fs.writeFileSync(
`${buildDir}/images/${_editionCount}.png`,
canvas.toBuffer("image/png")
);
};
const genColor = () => {
let hue = Math.floor(Math.random() * 360);
let pastel = `hsl(${hue}, 100%, ${background.brightness})`;
return pastel;
};
const drawBackground = () => {
ctx.fillStyle = background.static ? background.default : genColor();
ctx.fillRect(0, 0, format.width, format.height);
};
const addMetadata = (_dna, _edition) => {
let dateTime = Date.now();
let tempMetadata = {
name: `${namePrefix} #${_edition}`,
description: description,
image: `${baseUri}/${_edition}.png`,
dna: sha1(_dna),
edition: _edition,
date: dateTime,
...extraMetadata,
attributes: attributesList,
compiler: "CryptoGioconda Engine",
};
if (network == NETWORK.sol) {
tempMetadata = {
//Added metadata for solana
name: tempMetadata.name,
symbol: solanaMetadata.symbol,
description: tempMetadata.description,
//Added metadata for solana
seller_fee_basis_points: solanaMetadata.seller_fee_basis_points,
image: `image.png`,
//Added metadata for solana
external_url: solanaMetadata.external_url,
edition: _edition,
...extraMetadata,
attributes: tempMetadata.attributes,
properties: {
files: [
{
uri: "image.png",
type: "image/png",
},
],
category: "image",
creators: solanaMetadata.creators,
},
};
}
metadataList.push(tempMetadata);
attributesList = [];
};
const addAttributes = (_element) => {
let selectedElement = _element.layer.selectedElement;
attributesList.push({
trait_type: _element.layer.name,
value: selectedElement.name,
});
};
const loadLayerImg = async (_layer) => {
return new Promise(async (resolve) => {
const image = await loadImage(`${_layer.selectedElement.path}`);
resolve({ layer: _layer, loadedImage: image });
});
};
const addText = (_sig, x, y, size) => {
ctx.fillStyle = text.color;
ctx.font = `${text.weight} ${size}pt ${text.family}`;
ctx.textBaseline = text.baseline;
ctx.textAlign = text.align;
ctx.fillText(_sig, x, y);
};
const drawElement = (_renderObject, _index, _layersLen) => {
ctx.globalAlpha = _renderObject.layer.opacity;
ctx.globalCompositeOperation = _renderObject.layer.blend;
text.only
? addText(
`${_renderObject.layer.name}${text.spacer}${_renderObject.layer.selectedElement.name}`,
text.xGap,
text.yGap * (_index + 1),
text.size
)
: ctx.drawImage(
_renderObject.loadedImage,
0,
0,
format.width,
format.height
);
addAttributes(_renderObject);
};
const constructLayerToDna = (_dna = "", _layers = []) => {
let mappedDnaToLayers = _layers.map((layer, index) => {
let selectedElement = layer.elements.find(
(e) => e.id == cleanDna(_dna.split(DNA_DELIMITER)[index])
);
return {
name: layer.name,
blend: layer.blend,
opacity: layer.opacity,
selectedElement: selectedElement,
};
});
return mappedDnaToLayers;
};
/**
* In some cases a DNA string may contain optional query parameters for options
* such as bypassing the DNA isUnique check, this function filters out those
* items without modifying the stored DNA.
*
* #param {String} _dna New DNA string
* #returns new DNA string with any items that should be filtered, removed.
*/
const filterDNAOptions = (_dna) => {
const dnaItems = _dna.split(DNA_DELIMITER);
const filteredDNA = dnaItems.filter((element) => {
const query = /(\?.*$)/;
const querystring = query.exec(element);
if (!querystring) {
return true;
}
const options = querystring[1].split("&").reduce((r, setting) => {
const keyPairs = setting.split("=");
return { ...r, [keyPairs[0]]: keyPairs[1] };
}, []);
return options.bypassDNA;
});
return filteredDNA.join(DNA_DELIMITER);
};
/**
* Cleaning function for DNA strings. When DNA strings include an option, it
* is added to the filename with a ?setting=value query string. It needs to be
* removed to properly access the file name before Drawing.
*
* #param {String} _dna The entire newDNA string
* #returns Cleaned DNA string without querystring parameters.
*/
const removeQueryStrings = (_dna) => {
const query = /(\?.*$)/;
return _dna.replace(query, "");
};
const isDnaUnique = (_DnaList = new Set(), _dna = "") => {
const _filteredDNA = filterDNAOptions(_dna);
return !_DnaList.has(_filteredDNA);
};
const createDna = (_layers) => {
let randNum = [];
_layers.forEach((layer) => {
var totalWeight = 0;
layer.elements.forEach((element) => {
totalWeight += element.weight;
});
// number between 0 - totalWeight
let random = Math.floor(Math.random() * totalWeight);
for (var i = 0; i < layer.elements.length; i++) {
// subtract the current weight from the random weight until we reach a sub zero value.
random -= layer.elements[i].weight;
if (random < 0) {
return randNum.push(
`${layer.elements[i].id}:${layer.elements[i].filename}${
layer.bypassDNA ? "?bypassDNA=true" : ""
}`
);
}
}
});
return randNum.join(DNA_DELIMITER);
};
const writeMetaData = (_data) => {
fs.writeFileSync(`${buildDir}/json/_metadata.json`, _data);
};
const saveMetaDataSingleFile = (_editionCount) => {
let metadata = metadataList.find((meta) => meta.edition == _editionCount);
debugLogs
? console.log(
`Writing metadata for ${_editionCount}: ${JSON.stringify(metadata)}`
)
: null;
fs.writeFileSync(
`${buildDir}/json/${_editionCount}.json`,
JSON.stringify(metadata, null, 2)
);
};
function shuffle(array) {
let currentIndex = array.length,
randomIndex;
while (currentIndex != 0) {
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex--;
[array[currentIndex], array[randomIndex]] = [
array[randomIndex],
array[currentIndex],
];
}
return array;
}
const startCreating = async () => {
let layerConfigIndex = 0;
let editionCount = 1;
let failedCount = 0;
let abstractedIndexes = [];
for (
let i = network == NETWORK.sol ? 0 : 1;
i <= layerConfigurations[layerConfigurations.length - 1].growEditionSizeTo;
i++
) {
abstractedIndexes.push(i);
}
if (shuffleLayerConfigurations) {
abstractedIndexes = shuffle(abstractedIndexes);
}
debugLogs
? console.log("Editions left to create: ", abstractedIndexes)
: null;
while (layerConfigIndex < layerConfigurations.length) {
const layers = layersSetup(
layerConfigurations[layerConfigIndex].layersOrder
);
while (
editionCount <= layerConfigurations[layerConfigIndex].growEditionSizeTo
) {
let newDna = createDna(layers);
if (isDnaUnique(dnaList, newDna)) {
let results = constructLayerToDna(newDna, layers);
let loadedElements = [];
results.forEach((layer) => {
loadedElements.push(loadLayerImg(layer));
});
await Promise.all(loadedElements).then((renderObjectArray) => {
debugLogs ? console.log("Clearing canvas") : null;
ctx.clearRect(0, 0, format.width, format.height);
if (gif.export) {
hashlipsGiffer = new HashlipsGiffer(
canvas,
ctx,
`${buildDir}/gifs/${abstractedIndexes[0]}.gif`,
gif.repeat,
gif.quality,
gif.delay
);
hashlipsGiffer.start();
}
if (background.generate) {
drawBackground();
}
renderObjectArray.forEach((renderObject, index) => {
drawElement(
renderObject,
index,
layerConfigurations[layerConfigIndex].layersOrder.length
);
if (gif.export) {
hashlipsGiffer.add();
}
});
if (gif.export) {
hashlipsGiffer.stop();
}
debugLogs
? console.log("Editions left to create: ", abstractedIndexes)
: null;
saveImage(abstractedIndexes[0]);
addMetadata(newDna, abstractedIndexes[0]);
saveMetaDataSingleFile(abstractedIndexes[0]);
console.log(
`Created edition: ${abstractedIndexes[0]}, with DNA: ${sha1(
newDna
)}`
);
});
dnaList.add(filterDNAOptions(newDna));
editionCount++;
abstractedIndexes.shift();
} else {
console.log("DNA exists!");
failedCount++;
if (failedCount >= uniqueDnaTorrance) {
console.log(
`You need more layers or elements to grow your edition to ${layerConfigurations[layerConfigIndex].growEditionSizeTo} artworks!`
);
process.exit();
}
}
}
layerConfigIndex++;
}
writeMetaData(JSON.stringify(metadataList, null, 2));
};
module.exports = { startCreating, buildSetup, getElements };
I tried to use this code by inserting it inside the main document, but it doesn't work.
try {
fs.unlinkSync(path)
//file removed
} catch(err) {
console.error(err)
}
Can anyone tell me how can I solve?

Cannot read property 'target' of undefined Function remove not working

I have an array that has 3 contacts. I want the same person's name to be deleted when I click on the delete button, but unfortunately I do not know where the problem is that it does not work.
I have two functions in this program, one removeContact to perform the delete operation
And I have a function called showrecords to get the content of the array and display the name and number of contacts with a dedicated delete button for each contact
In this program, I used the pattern builder pattern
Please guide me to the conclusion to solve the problem of not being deleted
Please click on the show Person button to test the program. Contacts will be displayed and click on the delete button. You will see that the delete operation is not performed.
function ElementBuilder(name) {
this.element = document.createElement(name);
this.appendSelector = function(selector) {
this.appendElement = document.querySelector(selector).appendChild(this.element);
return this
};
this.setAttribute = function(attribute, valueAttribute) {
this.element.setAttribute(attribute, valueAttribute)
return this;
};
this.addEventListener = function(event, fun) {
this.element.addEventListener(event, fun);
return this;
};
this.text = function(text) {
this.element.textContent = text;
return this;
};
this.build = function() {
return this.element;
};
}
const builder = {
create: function(name) {
return new ElementBuilder(name);
}
};
function PhoneBook() {
this.records = [{ name: "niloufar", phone: 1111 }, { name: "sara", phone: 2222 }, { name: "sara", phone: 3333 }];
// function remove
this.removeContact = function() {
const self = this
function removePerson(item) {
if (item.target.classList.contains('delbutton')) {
const remID = item.target.getAttribute('data-id');
self.records.splice(remID, 1);
}
}
return removePerson;
}
}
function Render(container) {
this.container = container;
const phoneBook = new PhoneBook();
const remove = phoneBook
.removeContact();
this.removeEntry = (item) => {
remove(item); //
this.showrecords();
}
this.init = function() {
const btn = builder
.create("button")
.text("show person")
.addEventListener("click", this.showrecords)
.appendSelector("div")
.build();
};
// Function: Read contacts from the array and display them
this.showrecords = () => {
const addBookId = document.getElementById('phone-book-container');
let index = 0;
addBookId.innerHTML = '';
const arry = phoneBook.records;
arry.forEach(elm => {
const nameContent = builder
.create('p')
.text(`${elm.name}`)
.appendSelector("div")
.build();
const phoneContent = builder
.create('p')
.text(`${elm.phone}`)
.appendSelector("div")
.build();
const anchor = builder
.create('a')
.addEventListener('click', this.removeEntry)
.setAttribute('href', '#')
.setAttribute('class', 'delbutton')
.setAttribute("id", "deleteButton")
.text("delete")
.setAttribute('date-id', `${index}`)
.appendSelector("div")
.build();
});
}
}
const phoneBookContainer = document.getElementById("phone-book-container");
const app = new Render(phoneBookContainer);
app.init();
<div id="phone-book-container"></div>
You have to pass the item (which is actually the event object) to your function:
function ElementBuilder(name) {
this.element = document.createElement(name);
this.appendSelector = function(selector) {
this.appendElement = document.querySelector(selector).appendChild(this.element);
return this
};
this.setAttribute = function(attribute, valueAttribute) {
this.element.setAttribute(attribute, valueAttribute)
return this;
};
this.addEventListener = function(event, fun) {
this.element.addEventListener(event, fun);
return this;
};
this.text = function(text) {
this.element.textContent = text;
return this;
};
this.build = function() {
return this.element;
};
}
const builder = {
create: function(name) {
return new ElementBuilder(name);
}
};
function PhoneBook() {
this.records = [{ name: "niloufar", phone: 1111 }, { name: "sara", phone: 2222 }, { name: "sara", phone: 3333 }];
// function remove
this.removeContact = function() {
const self = this
function removePerson(item) {
if (item.target.classList.contains('delbutton')) {
const remID = item.target.getAttribute('date-id');
self.records.splice(remID, 1);
}
}
return removePerson;
}
}
function Render(container) {
this.container = container;
const phoneBook = new PhoneBook();
const remove = phoneBook
.removeContact();
this.removeEntry = (item) => {
remove(item);
this.showrecords();
}
this.init = function() {
const btn = builder
.create("button")
.text("show person")
.addEventListener("click", this.showrecords)
.appendSelector("div")
.build();
};
// Function: Read contacts from the array and display them
this.showrecords = () => {
const addBookId = document.getElementById('phone-book-container');
addBookId.innerHTML = '';
const arry = phoneBook.records;
arry.forEach((elm, index) => {
const nameContent = builder
.create('p')
.text(`${elm.name}`)
.appendSelector("div")
.build();
const phoneContent = builder
.create('p')
.text(`${elm.phone}`)
.appendSelector("div")
.build();
const anchor = builder
.create('a')
.addEventListener('click', this.removeEntry)
.setAttribute('href', '#')
.setAttribute('class', 'delbutton')
.setAttribute("id", "deleteButton")
.text("delete")
.setAttribute('date-id', `${index}`)
.appendSelector("div")
.build();
});
}
}
const phoneBookContainer = document.getElementById("phone-book-container");
const app = new Render(phoneBookContainer);
app.init();
<div id="phone-book-container"></div>

module.exports with function

I have several JavaScript files that I create enums. for example:
source.enum.js
const enumUtils = require('../enum.utils');
const EmailAddressesSourceType = enumUtils.createEnum([
['DIRECTORY', 'directory'],
['FILE', 'file'],
['ARRAY', 'array']
]);
module.exports = { EmailAddressesSourceType };
The enum.utils.js is just a file that do the simple function of creating an enum from array:
class EnumUtils {
constructor() { }
// This method takes a map of elements and converts them to freeze objects (an enum-like object).
createEnum(mapItems) {
if (!mapItems || mapItems.length <= 0) {
throw new Error(`No array received: ${mapItems} (1000000)`);
}
const mapList = new Map([...mapItems]);
const symbolMap = {};
mapList.forEach((value, key) => { symbolMap[key] = value; });
return Object.freeze(symbolMap);
}
}
const enumUtils = new EnumUtils();
module.exports = enumUtils;
Now since I have 5-6 js files with enums, I want to avoid 'const enumUtils = require('../enum.utils');' in each of them, and do it all together in index.js file, something like this:
const { EmailAddressStatus, EmailAddressType, SendEmailStepName } = require('./files/emailAddress.enum');
const { Placeholder } = require('./files/placeholder.enum');
const { EmailAddressesSourceType } = require('./files/sources.enum');
const { Mode, Status, Method } = require('./files/system.enum');
const { StatusIcon, Color, ColorCode } = require('./files/text.enum');
const createEnum = (mapItems) => {
if (!mapItems || mapItems.length <= 0) {
throw new Error(`No array received: ${mapItems} (1000000)`);
}
const mapList = new Map([...mapItems]);
const symbolMap = {};
mapList.forEach((value, key) => { symbolMap[key] = value; });
return Object.freeze(symbolMap);
};
module.exports = {
createEnum(Color), createEnum(ColorCode), createEnum(EmailAddressStatus), createEnum(EmailAddressType), createEnum(EmailAddressesSourceType),
createEnum(Method), createEnum(Mode), createEnum(Placeholder), createEnum(SendEmailStepName), createEnum(Status), createEnum(StatusIcon)
};
But, there are compilation error in:
module.exports = {
createEnum(Color), createEnum(ColorCode), createEnum(EmailAddressStatus), createEnum(EmailAddressType), createEnum(EmailAddressesSourceType),
createEnum(Method), createEnum(Mode), createEnum(Placeholder), createEnum(SendEmailStepName), createEnum(Status), createEnum(StatusIcon)
};
My question is, there is a workaround so enable me to reduce the 'const enumUtils = require('../enum.utils');' in each file of the enums js file?
Thanks!
UPDATE 1
The error I'm getting is this:
The current status of the file (before I was trying to refactor) - It works OK:
index.js
const { EmailAddressStatus, EmailAddressType, SendEmailStepName } = require('./files/emailAddress.enum');
const { Placeholder } = require('./files/placeholder.enum');
const { EmailAddressesSourceType } = require('./files/sources.enum');
const { Mode, Status, Method } = require('./files/system.enum');
const { StatusIcon, Color, ColorCode } = require('./files/text.enum');
module.exports = {
Color, ColorCode, EmailAddressStatus, EmailAddressType, EmailAddressesSourceType,
Method, Mode, Placeholder, SendEmailStepName, Status, StatusIcon
};
This guy, guy-incognito, solved for me the issue. Now it works like a charm. Thanks man!
const { EmailAddressStatus, EmailAddressType, SendEmailStepName } = require('./files/emailAddress.enum');
const { Placeholder } = require('./files/placeholder.enum');
const { EmailAddressesSourceType } = require('./files/sources.enum');
const { Mode, Status, Method } = require('./files/system.enum');
const { StatusIcon, Color, ColorCode } = require('./files/text.enum');
const createEnum = (mapItems) => {
if (!mapItems || mapItems.length <= 0) {
throw new Error(`No array received: ${mapItems} (1000000)`);
}
const mapList = new Map([...mapItems]);
const symbolMap = {};
mapList.forEach((value, key) => { symbolMap[key] = value; });
return Object.freeze(symbolMap);
};
module.exports = {
Color: createEnum(Color),
ColorCode: createEnum(ColorCode),
EmailAddressStatus: createEnum(EmailAddressStatus),
EmailAddressType: createEnum(EmailAddressType),
EmailAddressesSourceType: createEnum(EmailAddressesSourceType),
Method: createEnum(Method),
Mode: createEnum(Mode),
Placeholder: createEnum(Placeholder),
SendEmailStepName: createEnum(SendEmailStepName),
Status: createEnum(Status),
StatusIcon: createEnum(StatusIcon)
};

How do I pass index number to a react class?

Need help passing data "locationpos"= index of my Locations[] from function to class. I'm very new to React and I'm not sure what I'm doing wrong.
ERROR
Failed to compile
./src/components/data.js
Line 20:30: 'locationpos' is not defined no-undef
Search for the keywords to learn more about each error.
This error occurred during the build time and cannot be dismissed.
class Data {
constructor(locationpos) {
this.locationpos=locationpos;
this.updateData();
}
getTimes(date = null) {
date = date === null ? moment().format('DD/MM/YYYY') : date;
var data = this.getData();
return data ? data[date] : [];
}
getSpeadsheetUrl() {
return config.myData[locationpos];
}
function Daily({ locationProps = 1, root }) {
const context = useContext(ThemeContext);
const localization = useCallback(() => {
if (root && cookies.get("location") !== undefined) {
return cookies.get("location");
}
return locationProps;
}, [locationProps, root]);
const [locationState] = useState(localization());
const handleClick = event => {
window.focus();
notification.close(event.target.tag);
};
const openNav = () => {
document.getElementById("sidenav").style.width = "100%";
};
const closeNav = e => {
e.preventDefault();
document.getElementById("sidenav").style.width = "0";
};
// eslint-disable-next-line
const locationpos = locations.indexOf(locations[locationState]);
const _data = useRef(new Data(locationpos));
const getTimes = () => _data.current.getTimes();
Inside your data class, you need to use the instance variable as this.locationPos
getSpeadsheetUrl() {
return config.myData[this.locationpos];
}

How to pass data to afterClosed() in Angular Material Dialog in Angular 6

I am trying to pass data from a Dialog back to the component from which the user opened the dialog from. My simple example is below:
test.component.ts
import { xDialogComponent } from './../x-dialog/x-dialog.component';
import { xFilter } from './x-filter';
import { xLevelResult, xmodelResult, xpayResult, xpayClassResult, xSpResult } from './../database.service';
import { Component, OnInit } from '#angular/core';
import { FormArray, FormControl, FormGroup, Validators } from '#angular/forms';
import { databaseService, xSigResult, xOutResult, CurxpayResult } from '../database.service';
import { HttpClient } from '#angular/common/http';
import { NgIf } from '#angular/common/src/directives/ng_if';
import { element } from 'protractor';
import { ActivatedRoute } from '#angular/router';
import { MakeGroup, xpayteamResult, xpayteamSPResult, NoticeResult } from '../database.service';
import { DateResult } from '../database.service';
import { DatePipe } from '#angular/common';
import { Router } from '#angular/router';
import {MatSortModule} from '#angular/material/sort';
import {BrowserAnimationsModule} from '#angular/platform-browser/animations';
import {MatButtonModule, MatCheckboxModule} from '#angular/material';
import {MatTabsModule} from '#angular/material/tabs';
import {Observable, forkJoin} from 'rxjs';
import {mergeMap, expand, map, flatMap, concat, switchMap, combineAll} from 'rxjs/operators';
import {MatGridListModule} from '#angular/material/grid-list';
import {MatFormFieldModule} from '#angular/material/form-field';
import { MatInputModule, MatTableModule, MatPaginatorModule } from '#angular/material';
import { FormsModule } from '#angular/forms';
import {MatSnackBar} from '#angular/material';
import { MakeService } from './../../Make.service';
import {MatDialogModule} from '#angular/material/dialog';
import {MatDialogRef, MAT_DIALOG_DATA, MatDialog} from '#angular/material/dialog';
#Component({
selector: 'app-x',
templateUrl: './x.component.html',
styleUrls: ['../style.css']
})
export class xComponent implements OnInit {
MakeGroups: MakeGroup[];
xLevelresults: Array<xLevelResult>;
xmodelresults: Array<xmodelResult>;
xsigresults: Array<xSigResult>;
curxpayresults: Array<CurxpayResult>;
xpayresults: Array<xpayResult>;
xpayclassresults: Array<xpayClassResult>;
xpayteamresults: Array<xpayteamResult>;
xpayteamspresults: Array<xpayteamSPResult>;
FinalArray: any[] = [];
x_sp_results: Array<xSpResult>;
noticeresults: Array<NoticeResult>;
modelName: string;
TransactionDate: string;
MakeName: string;
delete: string;
dateselect: string;
noticedays: number;
selectedEffect: number;
// Disablers
SubmitDisabled: boolean;
AmountDisabled: boolean;
DateDisabled: boolean;
ISDisabled: boolean;
modelDisabled: boolean;
SigDisabled: boolean;
editswitch: boolean;
nextswitch: boolean;
// Selection variables for SP Call
selectedLevel: number;
selectedAmount: number;
selectedmodelNbr: number;
selectedClassId: number;
Advteam_DRAW_REPAY: number;
selectedSigId: number;
// SP Call
xspcall: string;
// Date variables
date: Date;
selectedDate = '';
success: boolean;
tomorrow: number;
yformat = '';
// x Outstanding
xoutresults: Array<xOutResult>;
x: number;
constructor(
private databaseService: databaseService,
private route: ActivatedRoute,
private router: Router,
private MakeService: MakeService,
public dialogx: MatDialog,
public snackBar: MatSnackBar
) {}
// changes the actual value of the variable for selectedLevel based on user selection
changedLevel (xLevelresult: xLevelResult) {
// Disable to ensure user enters correct data
this.SubmitDisabled = true;
this.DateDisabled = true;
this.SigDisabled = true;
this.xpayresults = [];
this.xsigresults = [];
this.selectedDate = undefined;
this.selectedSigId = undefined;
this.xpayclassresults = [];
this.xpayteamresults = [];
this.xpayteamspresults = [];
this.curxpayresults = [];
this.FinalArray = [];
this.selectedAmount = undefined;
this.selectedLevel = (xLevelresult ? xLevelresult.Make_Level_Id : 1);
console.log(this.selectedLevel);
// Populate model Drop-Down
const id = this.route.snapshot.paramMap.get('id');
this.databaseService.getxmodel(id, this.selectedLevel)
.subscribe(xmodelresults => this.xmodelresults = xmodelresults);
}
// changes the actual value of the variable for selectedmodelNbr based on user selection
changedmodel (xmodelresult: xmodelResult) {
this.SubmitDisabled = true;
this.DateDisabled = true;
this.SigDisabled = true;
this.selectedDate = undefined;
this.xpayresults = [];
this.xsigresults = [];
this.selectedSigId = undefined;
this.xpayclassresults = [];
this.xpayteamresults = [];
this.xpayteamspresults = [];
this.curxpayresults = [];
this.FinalArray = [];
this.selectedAmount = undefined;
this.selectedmodelNbr = (xmodelresult ? xmodelresult.model_Nbr : 1 );
console.log(this.selectedmodelNbr);
}
// // changes the actual value of the variable for selectedAmount based on user selection
changedAmount (event: any) {
if (this.editswitch === true) {
this.SubmitDisabled = true;
this.DateDisabled = true;
this.selectedAmount = event.target.value;
this.xpayresults = [];
this.xpayclassresults = [];
this.xpayteamresults = [];
this.xpayteamspresults = [];
this.curxpayresults = [];
this.FinalArray = [];
const id = this.route.snapshot.paramMap.get('id');
// change all values
this.selectedDate = this.xoutresults[this.x].Calc_Dt;
this.selectedLevel = this.xoutresults[this.x].Make_Level_Id;
this.selectedmodelNbr = this.xoutresults[this.x].model_Nbr;
// Populate form Data
this.databaseService.getxLevel(id)
.subscribe(xLevelresults => this.xLevelresults = xLevelresults);
this.databaseService.getxmodel(id, this.selectedLevel)
.subscribe(xmodelresults => this.xmodelresults = xmodelresults);
this.databaseService.getxSig(id, this.selectedLevel, this.selectedDate)
.subscribe(xsigresults => this.xsigresults = xsigresults);
// Set Vals
this.modelName = this.xoutresults[this.x].model_Name;
this.TransactionDate = this.xoutresults[this.x].Calc_Dt;
this.MakeName = this.xoutresults[this.x].Make_Level_Name;
// Populate the outstanding x Requests effecting the current request
this.databaseService.getCurxpay(id, this.selectedmodelNbr, this.selectedLevel, this.selectedDate)
.subscribe(curxpayresults => this.curxpayresults = curxpayresults,
error => console.log('ERROR!'),
() => {
// Set the effect on Outs Prin
if (this.curxpayresults.length === 0) {
this.selectedEffect = 0;
} else {
this.selectedEffect = this.curxpayresults[0].Outstanding_Total;
}
// Populate model Level Data
this.databaseService.getxpay(id, this.selectedLevel, this.selectedmodelNbr, this.selectedAmount, this.selectedEffect )
.subscribe(xpayresults => this.xpayresults = xpayresults,
error => console.log('ERROR!'),
// Check that Max CMT can cover the request
() => { console.log(this.xpayresults[0].reaminder);
if (this.xpayresults[0].reaminder < 0 || this.xpayresults[0].total < 0) {
// snack
if (this.xpayresults[0].reaminder < 0) {
this.snackBar.open('You:: ' +
(this.xpayresults[0].reaminder * -1).toFixed(2), 'Close', { duration: 10000} );
} else {
this.snackBar.open('You: ' +
(this.xpayresults[0].total * -1).toFixed(2), 'Close', { duration: 10000} );
}
} else {
// Populate Class and team Level Data for Screen
this.databaseService.getxpayClass(id, this.selectedLevel, this.selectedmodelNbr, this.selectedAmount, this.selectedEffect)
.subscribe(
(xpayclassresults) => {
this.xpayclassresults = xpayclassresults;
for (const xpayclassresult of this.xpayclassresults) {
this.selectedClassId = xpayclassresult.Class_ID;
console.log(this.selectedClassId);
this.databaseService.getxpayteam(id, this.selectedLevel, this.selectedmodelNbr
, this.selectedAmount, this.selectedClassId, this.selectedEffect )
.subscribe((xpayteamresults) => {
this.xpayteamresults = xpayteamresults;
this.FinalArray.push(this.xpayteamresults);
}, error => console.log('ERROR!'),
() => {
this.DateDisabled = false;
this.SubmitDisabled = false;
});
}
});
// Get team Level Data for SP submissions
this.databaseService.getxpayteamSP(id, this.selectedLevel, this.selectedmodelNbr
, this.selectedAmount)
.subscribe(xpayteamspresults => this.xpayteamspresults = xpayteamspresults,
error => console.log('ERROR!'),
() => {
});
}
});
});
} if (this.nextswitch === true) {
this.SubmitDisabled = true;
this.DateDisabled = true;
this.selectedAmount = event.target.value;
this.xpayresults = [];
this.xpayclassresults = [];
this.xpayteamresults = [];
this.xpayteamspresults = [];
this.curxpayresults = [];
this.FinalArray = [];
const id = this.route.snapshot.paramMap.get('id');
// Populate the outstanding x Requests effecting the current request
this.databaseService.getCurxpay(id, this.selectedmodelNbr, this.selectedLevel, this.selectedDate)
.subscribe(curxpayresults => this.curxpayresults = curxpayresults,
error => console.log('ERROR!'),
() => {
// Set the effect on Outs Prin
if (this.curxpayresults.length === 0) {
this.selectedEffect = 0;
} else {
this.selectedEffect = this.curxpayresults[0].Outstanding_Total;
}
// Populate model Level Data
this.databaseService.getxpay(id, this.selectedLevel, this.selectedmodelNbr, this.selectedAmount, this.selectedEffect )
.subscribe(xpayresults => this.xpayresults = xpayresults,
error => console.log('ERROR!'),
// Check that Max CMT can cover the request
() => { console.log(this.xpayresults[0].reaminder);
if (this.xpayresults[0].reaminder < 0 || this.xpayresults[0].total < 0) {
// snack
if (this.xpayresults[0].reaminder < 0) {
this.snackBar.open('You:: ' +
(this.xpayresults[0].reaminder * -1).toFixed(2), 'Close', { duration: 10000} );
} else {
this.snackBar.open('You: ' +
(this.xpayresults[0].total * -1).toFixed(2), 'Close', { duration: 10000} );
}
} else {
// Populate Class and team Level Data for Screen
this.databaseService.getxpayClass(id, this.selectedLevel, this.selectedmodelNbr, this.selectedAmount, this.selectedEffect)
.subscribe(
(xpayclassresults) => {
this.xpayclassresults = xpayclassresults;
for (const xpayclassresult of this.xpayclassresults) {
this.selectedClassId = xpayclassresult.Class_ID;
console.log(this.selectedClassId);
this.databaseService.getxpayteam(id, this.selectedLevel, this.selectedmodelNbr
, this.selectedAmount, this.selectedClassId, this.selectedEffect )
.subscribe((xpayteamresults) => {
this.xpayteamresults = xpayteamresults;
this.FinalArray.push(this.xpayteamresults);
}, error => console.log('ERROR!'),
() => {
this.DateDisabled = false;
this.SubmitDisabled = false;
});
}
});
// Get team Level Data for SP submissions
this.databaseService.getxpayteamSP(id, this.selectedLevel, this.selectedmodelNbr
, this.selectedAmount)
.subscribe(xpayteamspresults => this.xpayteamspresults = xpayteamspresults,
error => console.log('ERROR!'),
() => {
});
}
});
});
} else {
this.xsigresults = [];
this.selectedSigId = undefined;
this.SubmitDisabled = true;
this.DateDisabled = true;
this.SigDisabled = false;
this.xpayresults = [];
this.xpayclassresults = [];
this.xpayteamresults = [];
this.xpayteamspresults = [];
this.curxpayresults = [];
this.FinalArray = [];
const id = this.route.snapshot.paramMap.get('id');
// Populate Signatory Drop-Down
this.databaseService.getxSig(id, this.selectedLevel, this.selectedDate)
.subscribe(xsigresults => this.xsigresults = xsigresults);
// change amount value
this.selectedAmount = event.target.value;
console.log(this.selectedAmount);
}
// Populate Values for Notice Days Drop-Down
const id = this.route.snapshot.paramMap.get('id');
this.databaseService.getNotice(id)
.subscribe(noticeresults => this.noticeresults = noticeresults,
error => console.log('ERROR!'),
() => {
if (this.selectedAmount > 0) {
this.noticedays = this.noticeresults[0].Min_Repay_Notice_Days;
console.log(this.noticedays);
} else {
this.noticedays = this.noticeresults[0].Min_Adv_Notice_Days;
}
});
}
// // changes the actual value of the variable for selectedSigId based on user selection
changedSig (xsigresult: xSigResult) {
this.SubmitDisabled = true;
this.DateDisabled = false;
this.selectedDate = undefined;
this.xpayresults = [];
this.xpayclassresults = [];
this.xpayteamresults = [];
this.xpayteamspresults = [];
this.curxpayresults = [];
this.FinalArray = [];
this.selectedSigId = (xsigresult ? xsigresult.Signatory_ID : 1 );
console.log(this.selectedSigId);
}
// changes the actual value of the variable for selectedDate based on user selection of the date and pulls corresponding data
changedDate (event: any) {
// Disable to ensure user enters correct data
this.DateDisabled = true;
this.SubmitDisabled = true;
// change date value
this.selectedDate = event.target.value;
console.log(this.selectedDate);
this.xpayresults = [];
this.xpayclassresults = [];
this.xpayteamresults = [];
this.xpayteamspresults = [];
this.curxpayresults = [];
this.FinalArray = [];
const id = this.route.snapshot.paramMap.get('id');
// Populate the outstanding x Requests effecting the current request
this.databaseService.getCurxpay(id, this.selectedmodelNbr, this.selectedLevel, this.selectedDate)
.subscribe(curxpayresults => this.curxpayresults = curxpayresults,
error => console.log('ERROR!'),
() => {
// Set the effect on Outs Prin
if (this.curxpayresults.length === 0) {
this.selectedEffect = 0;
} else {
this.selectedEffect = this.curxpayresults[0].Outstanding_Total;
}
// Populate model Level Data
this.databaseService.getxpay(id, this.selectedLevel, this.selectedmodelNbr, this.selectedAmount, this.selectedEffect )
.subscribe(xpayresults => this.xpayresults = xpayresults,
error => console.log('ERROR!'),
// Check that Max CMT can cover the request
() => { console.log(this.xpayresults[0].reaminder);
if (this.xpayresults[0].reaminder < 0 || this.xpayresults[0].total < 0) {
// snack
if (this.xpayresults[0].reaminder < 0) {
this.snackBar.open('You:: ' +
(this.xpayresults[0].reaminder * -1).toFixed(2), 'Close', { duration: 10000} );
} else {
this.snackBar.open('Yo: ' +
(this.xpayresults[0].total * -1).toFixed(2), 'Close', { duration: 10000} );
}
} else {
// Populate Class and team Level Data for Screen
this.databaseService.getxpayClass(id, this.selectedLevel, this.selectedmodelNbr, this.selectedAmount, this.selectedEffect)
.subscribe(
(xpayclassresults) => {
this.xpayclassresults = xpayclassresults;
for (const xpayclassresult of this.xpayclassresults) {
this.selectedClassId = xpayclassresult.Class_ID;
console.log(this.selectedClassId);
this.databaseService.getxpayteam(id, this.selectedLevel, this.selectedmodelNbr
, this.selectedAmount, this.selectedClassId, this.selectedEffect )
.subscribe((xpayteamresults) => {
this.xpayteamresults = xpayteamresults;
this.FinalArray.push(this.xpayteamresults);
}, error => console.log('ERROR!'),
() => {
this.DateDisabled = false;
this.SubmitDisabled = false;
});
}
});
// Get team Level Data for SP submissions
this.databaseService.getxpayteamSP(id, this.selectedLevel, this.selectedmodelNbr
, this.selectedAmount)
.subscribe(xpayteamspresults => this.xpayteamspresults = xpayteamspresults,
error => console.log('ERROR!'),
() => {
});
}
});
});
}
submit() {
this.DateDisabled = true;
this.ISDisabled = true;
this.modelDisabled = true;
this.SubmitDisabled = true;
this.AmountDisabled = true;
this.SigDisabled = true;
if (this.selectedAmount > 0) {
for (const xpayteamspresult of this.xpayteamspresults) {
this.Advteam_DRAW_REPAY = (xpayteamspresult.team_DRAW_REPAY * -1);
this.xspcall = ('\'' + this.selectedDate + '\',' +
xpayteamspresult.Make_Level_Debt_ID + ',' + xpayteamspresult.Make_Id +
',' + xpayteamspresult.Make_Level_Id + ',' + xpayteamspresult.Class_ID + ',' +
xpayteamspresult.Debt_ID + ',' + xpayteamspresult.team_ID + ',' +
xpayteamspresult.team_DRAW_REPAY + ',' + '0' + ',' + this.Advteam_DRAW_REPAY);
this.databaseService.getxSP(this.xspcall).subscribe(x_sp_results => this.x_sp_results = x_sp_results);
}
} else {
for (const xpayteamspresult of this.xpayteamspresults) {
this.xspcall = ('\'' + this.selectedDate + '\',' +
xpayteamspresult.Make_Level_Debt_ID + ',' + xpayteamspresult.Make_Id +
',' + xpayteamspresult.Make_Level_Id + ',' + xpayteamspresult.Class_ID + ',' +
xpayteamspresult.Debt_ID + ',' + xpayteamspresult.team_ID + ',' +
'0' + ',' + xpayteamspresult.team_DRAW_REPAY + ',' + xpayteamspresult.team_DRAW_REPAY);
this.databaseService.getxSP(this.xspcall).subscribe(x_sp_results => this.x_sp_results = x_sp_results);
}
}
const id = this.route.snapshot.paramMap.get('id');
this.router.navigate(['/dashboard', id]);
}
submitEditDel (val) {
this.dateselect = '';
this.delete = 'To DELETE an existing entry mark this 0 and submit.';
this.DateDisabled = true;
this.ISDisabled = true;
this.modelDisabled = true;
this.SubmitDisabled = true;
this.AmountDisabled = false;
this.SigDisabled = true;
this.x = val;
this.editswitch = true;
console.log(this.x);
this.xpayresults = [];
this.xpayclassresults = [];
this.xpayteamresults = [];
this.xpayteamspresults = [];
this.curxpayresults = [];
this.FinalArray = [];
const id = this.route.snapshot.paramMap.get('id');
// change all values
this.selectedDate = this.xoutresults[this.x].Calc_Dt;
this.selectedAmount = this.xoutresults[this.x].Advance;
this.selectedLevel = this.xoutresults[this.x].Make_Level_Id;
this.selectedmodelNbr = this.xoutresults[this.x].model_Nbr;
// Set Vals
this.modelName = this.xoutresults[this.x].model_Name;
this.TransactionDate = this.xoutresults[this.x].Calc_Dt;
this.MakeName = this.xoutresults[this.x].Make_Level_Name;
// Populate the outstanding x Requests effecting the current request
this.databaseService.getCurxpay(id, this.selectedmodelNbr, this.selectedLevel, this.selectedDate)
.subscribe(curxpayresults => this.curxpayresults = curxpayresults,
error => console.log('ERROR!'),
() => {
// Set the effect on Outs Prin
if (this.curxpayresults.length === 0) {
this.selectedEffect = 0;
} else {
this.selectedEffect = this.curxpayresults[0].Outstanding_Total;
}
// Populate model Level Data
this.databaseService.getxpay(id, this.selectedLevel, this.selectedmodelNbr, this.selectedAmount, this.selectedEffect )
.subscribe(xpayresults => this.xpayresults = xpayresults,
error => console.log('ERROR!'),
// Check that Max CMT can cover the request
() => { console.log(this.xpayresults[0].reaminder);
if (this.xpayresults[0].reaminder < 0 || this.xpayresults[0].total < 0) {
// snack
if (this.xpayresults[0].reaminder < 0) {
this.snackBar.open('You:: ' +
(this.xpayresults[0].reaminder * -1).toFixed(2), 'Close', { duration: 10000} );
} else {
this.snackBar.open('You:y: ' +
(this.xpayresults[0].total * -1).toFixed(2), 'Close', { duration: 10000} );
}
} else {
// Populate Class and team Level Data for Screen
this.databaseService.getxpayClass(id, this.selectedLevel, this.selectedmodelNbr, this.selectedAmount, this.selectedEffect)
.subscribe(
(xpayclassresults) => {
this.xpayclassresults = xpayclassresults;
for (const xpayclassresult of this.xpayclassresults) {
this.selectedClassId = xpayclassresult.Class_ID;
console.log(this.selectedClassId);
this.databaseService.getxpayteam(id, this.selectedLevel, this.selectedmodelNbr
, this.selectedAmount, this.selectedClassId, this.selectedEffect)
.subscribe((xpayteamresults) => {
this.xpayteamresults = xpayteamresults;
this.FinalArray.push(this.xpayteamresults);
}, error => console.log('ERROR!'),
() => {
this.AmountDisabled = false;
this.SubmitDisabled = false;
});
}
});
// Get team Level Data for SP submissions
this.databaseService.getxpayteamSP(id, this.selectedLevel, this.selectedmodelNbr
, this.selectedAmount)
.subscribe(xpayteamspresults => this.xpayteamspresults = xpayteamspresults,
error => console.log('ERROR!'),
() => {
});
}
});
});
}
openDialog(): void {
const id = this.route.snapshot.paramMap.get('id');
const dialogRef = this.dialogx.open(xDialogComponent, {
width: '880px' });
dialogRef.componentInstance.id = id;
dialogRef.componentInstance.Levelid = this.selectedLevel;
dialogRef.componentInstance.modelnbr = this.selectedmodelNbr;
dialogRef.componentInstance.selectedDate = this.selectedDate;
dialogRef.afterClosed().subscribe(result => {
console.log('The dialog was closed');
console.log(dialogRef.componentInstance.closeMessage);
// Clear All Arrays
this.selectedAmount = undefined;
this.nextswitch = true;
this.DateDisabled = true;
this.ISDisabled = true;
this.modelDisabled = true;
this.SubmitDisabled = true;
this.AmountDisabled = false;
this.SigDisabled = true;
this.xpayresults = [];
this.xpayclassresults = [];
this.xpayteamresults = [];
this.xpayteamspresults = [];
this.curxpayresults = [];
this.FinalArray = [];
const id = this.route.snapshot.paramMap.get('id');
this.selectedmodelNbr = 2;
// No need to change values as all will remain same except amount
});
}
ngOnInit() {
this.MakeService.changeUrlid(this.route.snapshot.paramMap.get('id'));
// returns the outstanding x Draw/Repay
const id = this.route.snapshot.paramMap.get('id');
this.databaseService.getxOut(id).subscribe(xoutresults => this.xoutresults = xoutresults);
// get the Make Level data
this.databaseService.getxLevel(id)
.subscribe(xLevelresults => this.xLevelresults = xLevelresults);
// Disable to ensure user enters correct data
this.SubmitDisabled = true;
this.DateDisabled = true;
this.SigDisabled = true;
// get data for the dynamically chose Make group
this.databaseService.getGroup(id)
.subscribe(MakeGroups => this.MakeGroups = MakeGroups);
// get today's and tomorrows's date
this.date = new Date();
this.tomorrow = (Date.now() + 86400000 );
// format tomorrow's date for the initial run (using tomorrow as this is in the Borrowing Base)
const d = new Date(this.tomorrow);
let ym = '' + (d.getMonth() + 1);
let yd = '' + d.getDate();
const yy = d.getFullYear();
if (ym.length < 2) {
ym = '0' + ym;
}
if (yd.length < 2) {
yd = '0' + yd;
}
const yformat = [yy, ym, yd].join('-');
}
}
test-dialog.component.ts
import { AppRoutingModule } from './../../app-routing.module';
import { Component, OnInit } from '#angular/core';
import {MatDialogModule} from '#angular/material/dialog';
import {MatDialogRef, MAT_DIALOG_DATA, MatDialog} from '#angular/material/dialog';
import { Inject } from '#angular/core';
import { Observable } from 'rxjs';
import { databaseService, NextxResult } from '../database.service';
import { TrackerResult } from '../database.service';
import { HttpClient } from '#angular/common/http';
import { element } from 'protractor';
import { ActivatedRoute, Router, RouterLink, Routes } from '#angular/router';
#Component({
selector: 'app-x-dialog',
templateUrl: './x-dialog.component.html',
styleUrls: ['../style.css']
})
export class xDialogComponent implements OnInit {
id: string;
nextxresults: Array<NextxResult>;
closeMessage: string;
constructor(
private databaseService: databaseService,
private route: ActivatedRoute,
private router: Router,
public dialogRef: MatDialogRef<xDialogComponent>,
#Inject(MAT_DIALOG_DATA) public data: any) { }
onClose(): void {
// set the closeMessage property here
this.closeMessage = 'Pizza!';
this.dialogRef.close(5);
}
screenClick(val) {
console.log(val);
}
ngOnInit() {
this.databaseService.getNextx(this.id)
.subscribe(nextxresults => this.nextxresults = nextxresults);
}
}
The console.log comes back as undefined, any idea why I am not getting "Pizza!"?
Updated with all the code for both files to hopefully add more insight into my issue. Really appreciate any help to get this sorted out!
This is a possible workaround, but not the correct solution. Your code should be working as-is (according to the documentation) so there is something else going on that is causing it to break. Without a lot more context into your code, it will be hard to determine exactly what the issue is. For now, you can try this:
test-dialog.component.ts
export class TestDialogComponent implements OnInit {
id: string;
nextresults: Array<NextResult>;
closeMessage: string = "";
constructor(
...
public dialogRef: MatDialogRef<TestDialogComponent>,
...) { }
onClose(): void {
// set the closeMessage property here
this.closeMessage = "Pizza!";
this.dialogRef.close('ref');
}
...
}
test.component.ts
openDialog() {
const id = this.route.snapshot.paramMap.get('id');
const dialogRef = this.dialog.open(TestDialogComponent, {
width: '880px' });
dialogRef.componentInstance.id = id;
dialogRef.afterClosed().subscribe(result => {
console.log('The dialog was closed');
// reference the closeMessage property here
console.log(dialogRef.componentInstance.closeMessage);
});
}
Component A calls the dialog open event
User type some values in the dialog component (Component B) and click on Save
Component B calls the
this.dialogRef.close(this.worksheetName.value) with the desired
return values
this.dialogRef.afterClosed().subscribe getting invoked with the value passed
Component A
addWorksheet(): void {
this.dialogRef = this.dialog.open(CreateWorksheetComponent, { width: '400px' });
this.afterClosed();
}
private afterClosed(): void {
this.dialogRef.afterClosed().subscribe((worksheetName: string) => {
console.log(worksheetName)
this.createWorksheet(worksheetName);
});
}
Component B
createWorksheet(): void {
if (this.worksheetName.valid) {
this.dialogRef.close(this.worksheetName.value);
}
}
errorMessage(): void {
return Config.ErrorMessages.InvalidWorksheetName;
}
cancel(): void {
this.dialogRef.close();
}
Component B HTML
<div>
<mat-form-field class="example-full-width">
<input matInput placeholder="Ansichtiname" [formControl]="worksheetName">
<mat-error *ngIf="worksheetName?.invalid">{{errorMessage()}}</mat-error>
</mat-form-field>
</div>
<mat-card-actions>
<button mat-button (click)="cancel()">Abbrechen</button>
<button mat-button (click)="createWorksheet()" [disabled]="worksheetName?.invalid">Speichern</button>
</mat-card-actions>

Categories