sorry I am new in angular and StackOverflow
I have 3 divs and I want to add background-color: red to all divs which status is requesting payment. It should make background color to the second and the third div but it makes to only the third
html
<div class="col-md-4 mb-4" *ngFor="let invoice of Invoices let i=index">
<div id="{{'activeInvoice'+i}}" class=" d-flex justify-content-between align-items-center w-100 card-header ">
<strong class="text-gray-dark">{{langVar.Invoice}} {{invoice.invoiceNumber}}</strong>
<i class="fa fa-info-circle" title="show Details" aria-hidden="true" (click)="showInvoiceDetailsModal(invoice.id)"></i>
</div>
</div>
for (var i = 0; i <= this.Invoices.length-1; i++) {
console.log("invoice num", this.Invoices[i].invoiceNumber);
console.log("order", this.Invoices[i].order.length);
for (var j = 0; j <= this.Invoices[i].order.length - 1; j++) {
console.log("STATUS", this.Invoices[i].order[j].status);
if (this.Invoices[i].order[j].status == 'requestingPayment') {
var elementValue = 'activeInvoice'+i;
setTimeout(() => {
document.getElementById(elementValue).classList.add("cardBackGround");
}, 1000);
}
else {}
}
}
you can conditionally add CSS classes in angular using ngClass
<div [ngClass]={'cardBackGround': true }> </div>
// apply your condition instead of true
Related
I have made a TODO app and added a counter to keep a count of the items in the list. If the counter hits zero, I've set it to re-show a message 'You currently have no tasks. Use the input field above to start adding.'
if(count === 0){
noTasksText.classList.remove('d-none');
}
In the console I print out the div and it doesn't have d-none in the class list any more which is what I want, however, in the actual DOM it does.
Here is a full example - https://codepen.io/tomdurkin/pen/LYdpXKJ?editors=1111
I really can't seem to work this out. I can't seem to interact with that div when the counter becomes zero, however I can get console logs etc to show when expected.
Any help would be appreciated!
const mainInput = document.querySelector('#main-input');
const todoContainer = document.querySelector('#todo-container');
const errorText = document.querySelector('#js-error');
const noTasksText = document.querySelector('.js-no-tasks')
let tasks = [];
let count = 0;
// focus input on load
window.onload = () => {
mainInput.focus();
const storedTasks = JSON.parse(localStorage.getItem('tasks'));
if (storedTasks != null && storedTasks.length > 0) {
// set count to number of pre-existing items
count = storedTasks.length
// hide the 'no tasks' text
noTasksText.classList.add('d-none');
// overwrite tasks array with stored tasks
tasks = storedTasks;
tasks.forEach(task => {
// Build the markup
const markup = `
<div class="js-single-task single-task border-bottom pt-2 pb-2">
<div class="row">
<div class="col d-flex align-items-center js-single-task-name">
<h5 class="mb-0" data-title="${task}">${task}</h5>
</div>
<div class="col d-flex justify-content-end">
<button class="js-remove-task d-block btn btn-danger">Remove Item</button>
</div>
</div>
</div>`;
// Append it to the container
todoContainer.innerHTML += markup;
});
} else {
if (noTasksText.classList.contains('d-none')) {
noTasksText.classList.remove('d-none');
}
}
};
// event listener for 'enter on input'
mainInput.addEventListener("keydown", e => {
// if error is showing, hide it!
if (!errorText.classList.contains('d-none')) {
errorText.classList.add('d-none');
}
if (e.key === "Enter") {
// Get the value of the input
let inputValue = mainInput.value;
if (inputValue) {
// Build the markup
const markup = `
<div class="js-single-task border-bottom pt-2 pb-2">
<div class="row">
<div class="col d-flex align-items-center js-single-task-name">
<h5 class="mb-0" data-title="${inputValue}">${inputValue}</h5>
</div>
<div class="col d-flex justify-content-end">
<button class="js-remove-task d-block btn btn-danger">Remove Item</button>
</div>
</div>
</div>`;
// hide 'no tasks' text
noTasksText.classList.add('d-none');
// Append it to the container
todoContainer.innerHTML += markup;
// Push value to 'tasks' array
tasks.push(inputValue);
// Put in localStorage
textTasks = JSON.stringify(tasks);
localStorage.setItem("tasks", textTasks);
// Reset the value of the input field
mainInput.value = '';
// add 1 to the count
count++
} else {
// Some very basic validation
errorText.classList.remove('d-none');
}
}
});
// remove task
todoContainer.addEventListener('click', (e) => {
// Find the button in the row that needs removing (bubbling)
const buttonIsDelete = e.target.classList.contains('js-remove-task');
if (buttonIsDelete) {
// Remove the HTML from the screen
e.target.closest('.js-single-task').remove();
// Grab the name of the single task
let taskName = e.target.closest('.js-single-task').querySelector('.js-single-task-name h5').getAttribute('data-title');
// filter out the selected word
tasks = tasks.filter(item => item != taskName);
textTasks = JSON.stringify(tasks);
localStorage.setItem("tasks", textTasks);
// update counter
count--
// check if counter is zero and re-show 'no tasks' text if true
if (count === 0) {
noTasksText.classList.remove('d-none');
console.log(noTasksText);
}
}
});
body {
background: #e1e1e1;
}
<div class="container">
<div class="row d-flex justify-content-center mt-5">
<div class="col-10 col-lg-6">
<div class="card p-3">
<h2>To dos</h2>
<p>
Use this app to keep a list of things you need to do
</p>
<input class="form-control" id="main-input" type="text" placeholder="Type your todo and hit enter..." class="w-100" />
<small id="js-error" class="text-danger d-none">
Please type a value and press enter
</small>
<hr />
<h4 class="mb-5">Your 'To dos'</h4>
<div id="todo-container">
<!-- todos append in here -->
<div class="js-no-tasks">
<small class="d-block w-100 text-center mb-3">
<i>
You currently have no tasks. Use the input field above to start adding
</i>
</small>
</div>
</div>
</div>
<!-- /card -->
</div>
</div>
</div>
Upon setting innerHTML by using += innerHTML the node noTasksText is lost, because browser processes the whole new set innerHTML and creates new objects. You can either retrieve noTasksText again after that, or append nodes using todoContainer.appendChild. I forked your pen and solved it with the latter solution.
https://codepen.io/aghosey/pen/wvmGwWd
You can do the following, it will work (here innerHTML is changing the DOM, so I added an extra function to recalculate elements after DOM is changed due to innerHTML):
var mainInput = document.querySelector("#main-input");
var todoContainer = document.querySelector("#todo-container");
var errorText = document.querySelector("#js-error");
var noTasksText = document.querySelector(".js-no-tasks");
let tasks = [];
let count = 0;
function getAllElements() {
mainInput = document.querySelector("#main-input");
todoContainer = document.querySelector("#todo-container");
errorText = document.querySelector("#js-error");
noTasksText = document.querySelector(".js-no-tasks");
}
// focus input on load
window.onload = () => {
mainInput.focus();
var storedTasks = JSON.parse(localStorage.getItem("tasks"));
if (storedTasks != null && storedTasks.length > 0) {
// set count to number of pre-existing items
count = storedTasks.length;
// hide the 'no tasks' text
noTasksText.classList.add("d-none");
// overwrite tasks array with stored tasks
tasks = storedTasks;
tasks.forEach((task) => {
// Build the markup
const markup = `
<div class="js-single-task single-task border-bottom pt-2 pb-2">
<div class="row">
<div class="col d-flex align-items-center js-single-task-name">
<h5 class="mb-0" data-title="${task}">${task}</h5>
</div>
<div class="col d-flex justify-content-end">
<button class="js-remove-task d-block btn btn-danger">Remove Item</button>
</div>
</div>
</div>`;
// Append it to the container
todoContainer.innerHTML += markup;
getAllElements();
});
} else {
if (noTasksText.classList.contains("d-none")) {
noTasksText.classList.remove("d-none");
}
}
};
// event listener for 'enter on input'
mainInput.addEventListener("keydown", (e) => {
// if error is showing, hide it!
if (!errorText.classList.contains("d-none")) {
errorText.classList.add("d-none");
}
if (e.key === "Enter") {
// Get the value of the input
let inputValue = mainInput.value;
if (inputValue) {
// Build the markup
const markup = `
<div class="js-single-task border-bottom pt-2 pb-2">
<div class="row">
<div class="col d-flex align-items-center js-single-task-name">
<h5 class="mb-0" data-title="${inputValue}">${inputValue}</h5>
</div>
<div class="col d-flex justify-content-end">
<button class="js-remove-task d-block btn btn-danger">Remove Item</button>
</div>
</div>
</div>`;
// hide 'no tasks' text
noTasksText.classList.add("d-none");
// Append it to the container
todoContainer.innerHTML += markup;
getAllElements();
// Push value to 'tasks' array
tasks.push(inputValue);
// Put in localStorage
textTasks = JSON.stringify(tasks);
localStorage.setItem("tasks", textTasks);
// Reset the value of the input field
mainInput.value = "";
// add 1 to the count
count++;
} else {
// Some very basic validation
errorText.classList.remove("d-none");
}
}
});
// remove task
todoContainer.addEventListener("click", (e) => {
// Find the button in the row that needs removing (bubbling)
const buttonIsDelete = e.target.classList.contains("js-remove-task");
if (buttonIsDelete) {
// Remove the HTML from the screen
e.target.closest(".js-single-task").remove();
// Grab the name of the single task
let taskName = e.target
.closest(".js-single-task")
.querySelector(".js-single-task-name h5")
.getAttribute("data-title");
// filter out the selected word
tasks = tasks.filter((item) => item != taskName);
textTasks = JSON.stringify(tasks);
localStorage.setItem("tasks", textTasks);
// update counter
count--;
// check if counter is zero and re-show 'no tasks' text if true
if (count === 0) {
noTasksText.classList.remove("d-none");
console.log(noTasksText);
}
}
});
body {
background: #e1e1e1;
}
<div class="container">
<div class="row d-flex justify-content-center mt-5">
<div class="col-10 col-lg-6">
<div class="card p-3">
<h2>To dos</h2>
<p>
Use this app to keep a list of things you need to do
</p>
<input class="form-control" id="main-input" type="text" placeholder="Type your todo and hit enter..." class="w-100" />
<small id="js-error" class="text-danger d-none">
Please type a value and press enter
</small>
<hr />
<h4 class="mb-5">Your 'To dos'</h4>
<div id="todo-container">
<!-- todos append in here -->
<div class="js-no-tasks">
<small class="d-block w-100 text-center mb-3">
<i>
You currently have no tasks. Use the input field above to start adding
</i>
</small>
</div>
</div>
</div>
<!-- /card -->
</div>
</div>
</div>
I am working on a chrome extension and trying to add an event listener to a getElementsByClassName variable, in which elements are added dynamically using template strings.
I have tried a lot of changes in the code, but the code doesn't work.
The code is supposed to delete the targeted element from the array "recipeList", storing the array in localStorage and then render the updated array "recipeList" using template string to the HTML code again.
DELETE BUTTON Function
let delBtn = document.getElementsByClassName("del-btn");
for(let i = 0; i < delBtn.length; i++) {
delBtn[i].addEventListener("click", function() {
recipeList.splice(i, 1);
localStorage.setItem("recipeList", JSON.stringify(recipeList));
recipeList = JSON.parse(localStorage.getItem("recipeList"));
render(recipeList);
if(!recipeList.length) {
tabBtn.style.width = "100%";
delAllBtn.style.display = "none";
}
});
}
RENDER CODE
function render(list) {
let recipeURL = "";
for(let i = 0; i < list.length; i++) {
recipeURL += `
<div class="mb-2 row">
<div class="col-1 num-btn">
${i+1}
</div>
<div class="col-10">
<div class="recipe-url">
<a target="_blank" href="${list[i]}">
${list[i]}
</a>
</div>
</div>
<div class="col-1 del-btn">
<a href="#">
<i class="bi bi-trash-fill"></i>
</a>
</div>
</div>
`
}
urlList.innerHTML = recipeURL;
console.log(delBtn);
}
When you render, you create new .del-btn which are not included in your first let delBtn = document.getElementsByClassName("del-btn");.
Each time you create new .del-btn, you should also add a new listener.
function render(list) {
let recipeURL = "";
for(let i = 0; i < list.length; i++) {
recipeURL += `
<div class="mb-2 row">
<div class="col-1 num-btn">
${i+1}
</div>
<div class="col-10">
<div class="recipe-url">
<a target="_blank" href="${list[i]}">
${list[i]}
</a>
</div>
</div>
<div class="col-1 del-btn">
<a href="#">
<i class="bi bi-trash-fill"></i>
</a>
</div>
</div>
`
}
urlList.innerHTML = recipeURL;
console.log(delBtn);
Array.from(urlList.querySelectorAll('.del-btn')).forEach((btn, i) => {
btn.addEventListener('click', () => console.log('.del-btn index: ' + i))
})
}
}
I am using a Bootstrap Carousel, but the slides of the carousel are generated through DOM by looping through an array called "Capris".
There is a button that displays on each slide that is also specific to each index.
What I am trying to do is when a User clicks on one of the buttons, it redirects them to a different HTML file and prints to DOM that same index, just on the other HTML page.
I managed to do everything except having that index print to DOM on the second HTML file. Here is a snippet of my code for the carousel and the button's event listener:
const buyCapriBttn = () => {
for (let i = 0; i < capris.length; i++) {
document.querySelector(`#${capris[i].name}`).addEventListener('click', function () {generateProduct(capris[i])});
}
}
const capriCarousel = () => {
let domString = '';
for (let i = 0; i < capris.length; i++) {
if (i === 0) {
domString += `
<div class="carousel-item active">
<img class="d-block w-100" src="${capris[i].imageUrl}" alt="Capri 1">
<div class="d-flex justify-content-center">
<a id="${capris[i].name}" class="btn btn-primary capri-btn" href="/capris.html" role="button">Buy ${capris[i].name}</a>
</div>
<p class="capri-description">${capris[i].description}</p>
</div>
`;
} else if (i >= 1) {
domString += `
<div class="carousel-item">
<img class="d-block w-100" src="${capris[i].imageUrl}" alt="Capri 1">
<div class="d-flex justify-content-center">
<a id="${capris[i].name}" class="btn btn-primary capri-btn" href="/capris.html" role="button">Buy ${capris[i].name}</a>
</div>
<p class="capri-description">${capris[i].description}</p>
</div>
`;
} else;
}
printToDom("#carousel-items", domString);
buyCapriBttn();
}
When the button is clicked, it runs the generateProduct function for that index. Here is a snippet of that function that is run:
const generateProduct = (selectedPants) => {
domString = '';
console.log(selectedPants);
for (let i = 0; i < capris.length; i++) {
if (capris[i] === selectedPants) {
domString += `
<div id="caprisDom">
<img id="buycaprispic" src="${capris[i].imageUrl}">
<div id="nameandrating">
<h5 id="buycaprisname">${capris[i].name}</h5><h2>☆☆☆☆☆</h2>
</div>
<div class="caprisinfobox">
<p id="caprisinfo">${capris[i].description}</p>
<div class="sizeandprice">
<div id="sizeselector">
<label id="sizelabel">Size:</label>
<select name="sizelist" id="size">
</select>
</div>
<h3 id="price">$${capris[i].price}</h3>
</div>
<button id="cartbutton">Add to Cart</button>
</div>
</div>
`;
}
}
printToDom('#caprismain', domString);
}
I have a printToDom function that prints to those ids if you need that as well.
NOTE: In this exercise, I am trying to not use JQuery
Any thoughts and help are much appreciated!
Is all you need the index position of the item? I'd probably add it dynamically in the a declaration. Something like <a id="${capris[i].name}" class="btn btn-primary capri-btn" href="/capris.html?index=${i}" role="button">Buy ${capris[i].name}</a>
So it should look like this:
const capriCarousel = () => {
let domString = '';
for (let i = 0; i < capris.length; i++) {
if (i === 0) {
domString += `
<div class="carousel-item active">
<img class="d-block w-100" src="${capris[i].imageUrl}" alt="Capri 1">
<div class="d-flex justify-content-center">
<a id="${capris[i].name}" class="btn btn-primary capri-btn" href="/capris.html?index=${i}" role="button">Buy ${capris[i].name}</a>
</div>
<p class="capri-description">${capris[i].description}</p>
</div>
`;
} else if (i >= 1) {
domString += `
<div class="carousel-item">
<img class="d-block w-100" src="${capris[i].imageUrl}" alt="Capri 1">
<div class="d-flex justify-content-center">
<a id="${capris[i].name}" class="btn btn-primary capri-btn" href="/capris.html?index=${i}" role="button">Buy ${capris[i].name}</a>
</div>
<p class="capri-description">${capris[i].description}</p>
</div>
`;
} else;
}
printToDom("#carousel-items", domString);
buyCapriBttn();
}
Then, in the other page, in your js, you'd grab the query select using URLSearchParams like so:
const urlParams = new URLSearchParams(window.location.search);
const myParam = urlParams.get('index');
I am making angular application with angular dynamic form where i am using ng-select library.
The HTML with select:
<div *ngFor="let question of questions" class="form-row {{question.class}}">
<ng-container *ngIf="question.children">
<div [formArrayName]="question.key" class="w-100">
<div *ngFor="let item of form.get(question.key).controls; let i=index" [formGroupName]="i" class="row mt-1">
<div *ngFor="let item of question.children" class="{{item.class}} align-middle">
<div class="w-100">
<dynamic-form-builder [question]="item" [index]="i" [form]="form.get(question.key).at(i)"></dynamic-form-builder>
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-6 col-sm-12 col-lg-6 col-md-6">
<div class="form-label-group" *ngIf="showTemplateDropdown">
<ngi-select placeholder="Select Template" [required]="true" [hideSelected]="false" [multiple]="true" [items]="templateList"
dropdownPosition="down" bindLabel="name" bindValue="id" (add)="getTemplateValues($event)" (remove)="onRemove($event)">
</ngi-select>
</div>
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-6 col-sm-12 col-lg-6 col-md-6">
</div>
<div class="col-6 col-sm-12 col-lg-6 col-md-6 text-right">
<div class="btn-group float-right">
<button class="btn btn-primary btn-round btn-fab mat-raised-button" mat-min-fab="" mat-raised-button="" type="button"
(click)="addControls('template_properties')">
<span class="mat-button-wrapper"><i class="material-icons mt-2">add</i></span>
<div class="mat-button-ripple mat-ripple" matripple=""></div>
<div class="mat-button-focus-overlay"></div>
</button>
<button class="btn btn-primary btn-round btn-fab mat-raised-button" mat-min-fab="" mat-raised-button="" type="button"
(click)="removeControls('template_properties')">
<span class="mat-button-wrapper"><i class="material-icons mt-2">remove</i></span>
<div class="mat-button-ripple mat-ripple" matripple=""></div>
<div class="mat-button-focus-overlay"></div>
</button>
</div>
</div>
</div>
</div>
</div>
</ng-container>
<ng-container *ngIf="!question.children">
<div class="w-100">
<dynamic-form-builder [question]="question" [form]="form"></dynamic-form-builder>
</div>
</ng-container>
</div>
Here the [items]="templateList" has the following,
[{"id":"5bebba2c20ccc52871509d56","name":"Template One"},
{"id":"5bebba5720ccc52871509d57","name":"Template Two"},
{"id":"5bebba8d20ccc52871509d5d","name":"Template Three"}]
I am having (change)="getTemplateValues($event)" event for detecting each change happen when we select an item from dropdown.
The change event function Edited,
getTemplateValues(e) {
this.dynamicFormService.getRest("url" + '/' + e.id").subscribe(res => {
try {
if (res.status === "true") {
res.data.template_properties.forEach(element => {
this.templateArray.push(element);
});
this.form = this.qcs.toFormGroup(this.questions);
for (let i = 0; i < this.templateArray.length; i++) {
this.addControls('template_properties');
}
let propertiesArray = [];
this.templateArray.forEach(element => {
propertiesArray.push(element);
});
this.form.patchValue({
'template_properties': propertiesArray
});
} else {
}
}
catch (error) {
}
})
}
console.log(this.propertiesArray) gives the following,
[{"property_name":"Property one","property_type":4,"property_required":true,"property_origin":1},{"property_name":"Property one","property_type":5,"property_required":true,"property_origin":1}]
In the below image i have deleted template three but the template three properties still showing in it..
Here first i am filtering the data first and ignoring the duplicates and each time i am sending the newly selected values alone to the service and fetching the data related to the id element.id.
And using this.addControls('template_properties') to make open the number of rows, and elements will get patched to the form template_properties.
this.form.patchValue({
'template_properties': propertiesArray
});
As of now everything working fine..
The problem actually arise from here:
If we delete a selected list from dropdown, (say i have selected all three template and i have deleted the template two then that particular template's template_properties needs to get deleted..
I have tried with (remove)="onRemove($event)" but its not working because while remove data, the (change) function also calls..
How can i remove the template_properties with this.removeControls('template_properties'); of particular deleted template name in the change event or remove event..
Remove Function:
onRemove(e) {
console.log(e);
this.dynamicFormService.getRest("url" + '/' + e.value.id").subscribe(res => {
try {
if (res.status === "true") {
for (let i = 0; i < res.data.template_properties.length; i++) {
this.removeControls('template_properties');
}
} else {
}
}
catch (error) {
}
})
}
Remove Control:
removeControls(control: string) {
let array = this.form.get(control) as FormArray;
console.log(array)
array.removeAt(array.length);
}
console.log(array) gives,
It should be pretty easy fix. Use (add) instead of (change) in ngi-select.
onRemove(e) {
console.log(e);
this.dynamicFormService.getRest("url" + '/' + e.value.id").subscribe(res => {
try {
if (res.status === "true") {
this.form = this.qcs.toFormGroup(this.questions);
// Issue is here, you should remove only specific record
// which is being passed from function `e`
for (let i = 0; i < res.data.template_properties.length; i++) {
this.removeControls('template_properties');
}
let propertiesArray = [];
this.templateArray.forEach(element => {
propertiesArray.push(element);
});
this.form.patchValue({
'template_properties': propertiesArray
});
} else {
}
}
catch (error) {
}
})
}
Pass the index in removeControls where you want to remove the element from.
removeControls(control: string, index:number) {
let array = this.form.get(control) as FormArray;
console.log(array)
array.removeAt(index);
}
console.log(array) gives,
I have a tab menu on my website and the code used for it works perfectly. JavaScript:
function openTab(tabName) {
var i;
var x = document.getElementsByClassName("tab");
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
document.getElementById(tabName).style.display = "flex";
}
HTML:
<div class="col-md-4">
<div onclick="openTab('tab-1')" class="tab-button">
<h5>IT Problems</h5>
</div>
</div>
<div class="col-md-4">
<div onclick="openTab('tab-2')" class="tab-button">
<h5>Save Time</h5>
</div>
</div>
<div class="col-md-4">
<div onclick="openTab('tab-3')" class="tab-button">
<h5>Cost Effective</h5>
</div>
</div>
And then obviously I applied the IDs ("tab-[1/2/3]") and classes ("tab") to the divs I want as tabs. However, when I replicate the exact same code to have a tab button highlighted for the current tab open, it doesn't work. JavaScript:
function selectedTab(selectName) {
var i;
var x = document.getElementsByClassName("select");
for (i = 0; i < x.length; i++) {
x[i].style.border-bottom-color = "#dbdbdb";
}
document.getElementById(selectName).style.border-bottom-color = "#25a7df";
}
HTML:
<div class="col-md-4">
<div onclick="openTab('tab-1'); selectedTab('select-1')" class="tab-button">
<h5 id="select-1" class="select">IT Problems</h5>
</div>
</div>
<div class="col-md-4">
<div onclick="openTab('tab-2'); selectedTab('select-2')" class="tab-button">
<h5 id="select-2" class="select">Save Time</h5>
</div>
</div>
<div class="col-md-4">
<div onclick="openTab('tab-3'); selectedTab('select-3')" class="tab-button">
<h5 id="select-3" class="select">Cost Effective</h5>
</div>
</div>
I've looked literally everywhere online and had multiple people look at this and nobody can find a solution. Can anyone help?
border-bottom-color is not a valid style property, you need to replace hyphen case with camel case
You need to use the borderBottomColor property of style in selectTab method
function selectedTab(selectName) {
var x = document.getElementsByClassName("select");
for (var i = 0; i < x.length; i++) {
x[i].style.borderBottomColor = "#dbdbdb"; //observe style property Change
}
document.getElementById(selectName).style.borderBottomColor = "#25a7df";
}