How to stop all items from being opened when editing item in ngFor loop - javascript

I have an array of objects and you can edit the name of each one but then I click to edit one all of the names of the items open, I am wondering how do to fix this.
<div *ngFor="let stop of fave; let i = index" attr.data="{{stop.Type}}">
<div class="card m-1">
<div class="card-body">
<div class="card-text">
<div class="row">
<label class="name" *ngIf="!toggleName" (click)="toggleName = true">{{stop.Name}}</label>
<div class="md-form" *ngIf="toggleName">
<input (keydown.enter)="updateStopName(i, stop.id); toggleName = false" placeholder="Chnage Stop Name" [(ngModel)]="stopName" required mdbInput type="text"
id="form1" class="form-control">
</div>
</div>
<div class="custom">
<img *ngIf="stop.Type === 'Train'" class="train-icon" style="width: 40px; height:40px"
src="assets/img/icon_trian.png" />
<img *ngIf="stop.Type === 'bus'" style="width: 40px; height:40px" src="assets/img/icon_bus.png" />
<img *ngIf="stop.Type === 'Luas'" style="width: 40px; height:40px"
src="assets/img/icon_tram.png" />
</div>
<label class="col-4 custom-label">Stop</label>
<label class="col-5 custom-service-label">Service</label>
<div class="row">
<span class="col-5 stop"> {{stop.StopNo}}</span>
<span style="padding-left:31%;" class="col-6 stop"> {{stop.Type | titlecase}}</span>
</div>
<hr />
<div class="row">
<div class="panel col-7" (click)="getRealtimeInfo({stop: stop.StopNo, type: stop.Type})">
<img class="panel-realtime" src="assets/img/icon_view.png" />
</div>
<div class="panel col-5" (click)="deleteFav(stop.id, i)">
<img class="panel-remove" src="assets/img/icon_remove.png" />
</div>
</div>
</div>
</div>
</div>
</div>
I know its something to do with the index but I am not sure how to write the code to only open the one I clicked on
As you can see at the moment all of them open any help is very much appreciated

If you want to open one at a time, you can use the index and of the item and a boolean. When clicked, set the index value to toggl if it's not already assigned, else assign it null (so that we can close the opened div on same click), and then show the content you want, when toggl === i. Something like:
<div *ngFor="let stop of fave; let i = index">
<label (click)="toggl === i ? toggl = null : toggl = i">Stuff!</label>
<div *ngIf="toggl === i">
<!-- ... -->
</div>
</div>
DEMO: StackBlitz

In your component declare one array
hideme=[];
In your html
<div *ngFor="let stop of fave; let i = index" attr.data="{{stop.Type}}">
<a (click)="hideme[i] = !hideme[i]">show/hide</a>
<div [hidden]="hideme[i]">The content will show/hide</div>
</div>

You have a unique id value inside your array, then you can do it like this:
<div *ngFor="let row of myDataList">
<div [attr.id]="row.myId">{{ row.myValue }}</div>
</div>
Assign an id to your input fields and they will work fine. Right now all of them have same id.

Use this code below as an example:
In your component, create a mapping like so:
itemStates: { [uniqueId: string]: boolean } = {};
Within your on click function:
itemClicked(uniqueId: string) {
let opened: boolean = this.itemStates[uniqueId];
if (opened !== undefined) {
opened = !opened; // Invert the result
} else {
opened = true;
}
}
In your HTML:
<div *ngFor="let item of items">
<h1 (click)="itemClicked(item.uniqueId)">{{ item.name }}</h1>
<div *ngIf="itemStates[item.uniqueId] == true">
<p>This item is open!</p>
</div>
</div>
Essentially, each item in your array should have a unique identifier. The itemStates object acts as a dictionary, with each unique ID having an associated true/false value indicating whether or not the item is open.
Edit: The accepted answer to this question is very simple and works great but this example may suit those who need to have the ability to have more than one item open at once.

Related

I can't find the container using an only child in JavaScript [duplicate]

This question already has answers here:
Getting the parent div of element
(7 answers)
Closed last month.
I have a project. I am working to find a container using an only child in JavaScript.
I want to add a class to the container of the req-address.
I want to take req in Javascript using an only child of this element. How to do it?
const search = document.querySelector('.search-form');
const addresses = document.querySelectorAll('.req-address');
search.addEventListener('keyup', function(e) {
addresses.forEach(function(address) {
if (address.innerHTML === search.value) {
address.classList.add('.search-active');
}
});
});
<div class="reqs-container">
<div class="req">
<div class="req-time">
<div class="req-time_from">13:00</div>
<span></span>
<div class="req-time_to">15:00</div>
</div>
<div class="req-restaurant">Argentina Grill</div>
<div class="req-address">Оболонь</div>
<div class="req-name">Аліна</div>
Instagram
Приєднатися
</div>
<div class="req">
<div class="req-time">
<div class="req-time_from">13:00</div>
<span></span>
<div class="req-time_to">15:00</div>
</div>
<div class="req-restaurant">Argentina Grill</div>
<div class="req-address">Хрещатик</div>
<div class="req-name">Аліна</div>
Instagram
Приєднатися
</div>
</div>
You needed to remove the dot from the class in .classList.add('.search-active')
To add to the parent div with class = req, you can use
address.closest('div.req')
Here is an alternative version which will toggle instead of just add.
Also I use input event since it handles paste too
Lastly I use includes, textContent, trim and toLowerCase to give the user a better chance to find stuff since innerHTML could have all sorts of whitespace
If you insist on the complete value in the address field must be typed to be found, change
address.textContent.toLowerCase().trim().includes(val)
to
address.textContent === val
const search = document.querySelector('.search-form');
const addresses = document.querySelectorAll('.req-address');
search.addEventListener('input', function(e) {
const val = this.value.toLowerCase();
addresses.forEach(address => address.closest('div.req').classList.toggle('search-active', address.textContent.toLowerCase().trim().includes(val)));
});
.search-active { color: green }
<input type="text" class="search-form" />
<div class="reqs-container">
<div class="req">
<div class="req-time">
<div class="req-time_from">13:00</div>
<span></span>
<div class="req-time_to">15:00</div>
</div>
<div class="req-restaurant">Argentina Grill</div>
<div class="req-address">Оболонь</div>
<div class="req-name">Аліна</div>
Instagram
Приєднатися
</div>
<div class="req">
<div class="req-time">
<div class="req-time_from">13:00</div>
<span></span>
<div class="req-time_to">15:00</div>
</div>
<div class="req-restaurant">Argentina Grill</div>
<div class="req-address">Хрещатик</div>
<div class="req-name">Аліна</div>
Instagram
Приєднатися
</div>
</div>

How to look for child elements in a collection

im very new to javascript and probably thats a silly question. What I am trying to achieve is to loop through rows of a "table", get the innerHTML of specific child nodes and multiply them together.
The html looks like this:
<div class="parent">
...
<div class="countChild">
<div class="container">
<span class="count">5</span>
</div>
</div>
<div class="valueChild">
<span class="value">30</span>
</div>
...
</div>
<div class="parent">
...
<div class="countChild">
<div class="container">
<span class="count">2</span>
</div>
</div>
<div class="valueChild">
<span class="value">30</span>
</div>
...
</div>
To be specific: I want to get both the values inside the'countChild' and the 'valueChild'. In this example those are 5 and 30 for the first row and for the second row its 2 and 30. Then perform a muiltiplication.
What I tried to do is to get all the parent nodes and then iterating through them to get the child nodes.
const parents = document.getElementsByClassName('parent');
for(var row in parents) {
var count = row.getElementsByClassName('countChild').lastChild.innerHTML;
var value = row.getElementsByClassName('valueChild').lastChild.innerHTML;
....
}
However the debugger already throws an error when im trying to get the childs. The error message is row.getElemenstByClassName is not a function. I guess the collection cannot be used like this and my understanding of how to use js to get information from the document is wrong.
Edit: This is what the tree looks like
<div class="listing-entry">
<div class="value-container d-none d-md-flex justify-content-end">
<div class="d-flex flex-column">
<div class="d-flex align-items-center justify-content-end">
<span class="font-weight-bold color-primary small text-right text-nowrap">30</span>
</div>
</div>
</div>
<div class="count-container d-none d-md-flex justify-content-end mr-3">
<span class="item-count small text-right">5</span>
</div>
</div>
You should access parents like an array (not really array but you can cast it to one). Btw, I encourage you to use querySelectorAll and querySelector instead of getElementsByClassName
const parents = document.querySelectorAll(".parent")
parents.forEach(function(row) {
var countChild = row.querySelector(".countChild")
var valueChild = row.querySelector(".valueChild")
var count = countChild ? countChild.innerText : 0
var value = valueChild ? valueChild.innerText : 0
console.log(count, value, count * value)
})
<div class="parent">
...
<div class="countChild">
<div class="container">
<span class="count">5</span>
</div>
</div>
<div class="valueChild">
<span class="value">30</span>
</div>
...
</div>
<div class="parent">
...
<div class="countChild">
<div class="container">
<span class="count">2</span>
</div>
</div>
<div class="valueChild">
<span class="value">30</span>
</div>
...
</div>
Edit: I'm using querySelector instead of getElementsByClassName, and checking if child exists before accessing its innerText property.
Edit: here's a function to get all text nodes under a specific node. Then you can combine them and trim the result to get the value you want.
function textNodesUnder(node) {
var all = [];
for (node = node.firstChild; node; node = node.nextSibling) {
if (node.nodeType == 3) {
all.push(node);
} else {
all = all.concat(this.textNodesUnder(node));
}
}
return all;
}
var nodes = textNodesUnder(document.querySelector(".listing-entry"))
var texts = nodes.map(item => item.nodeValue.trim())
console.log(texts)
<div class="listing-entry">
<div class="value-container d-none d-md-flex justify-content-end">
<div class="d-flex flex-column">
<div class="d-flex align-items-center justify-content-end">
<span class="font-weight-bold color-primary small text-right text-nowrap">30</span>
</div>
</div>
</div>
<div class="count-container d-none d-md-flex justify-content-end mr-3">
<span class="item-count small text-right">5</span>
</div>
</div>

Link simillary name classes so that when one is clicked the other is given a class

Basically, I'm asking for a way to optimize this code. I'd like to cut it down to a few lines because it does the same thing for every click bind.
$("#arch-of-triumph-button").click(function(){
$("#arch-of-triumph-info").addClass("active-info")
});
$("#romanian-athenaeum-button").click(function(){
$("#romanian-athenaeum-info").addClass("active-info")
});
$("#palace-of-parliament-button").click(function(){
$("#palace-of-parliament-info").addClass("active-info")
});
Is there a way to maybe store "arch-of-triumph", "romanian-athenaeum", "palace-of-parliament" into an array and pull them out into a click bind? I'm thinking some concatenation maybe?
$("+landmarkName+-button").click(function(){
$("+landmarkName+-info").addClass("active-info")
});
Is something like this even possible?
Thanks in advance for all your answers.
EDIT: Here's the full HTML.
<div class="landmark-wrapper">
<div class="page-content landmark">
<div class="heading span-after">
<span>Arch of Triumph</span>
</div>
<div class="landmark-button" id="arch-of-triumph-button"></div>
</div>
</div>
<div class="landmark-wrapper">
<div class="page-content landmark">
<div class="heading span-after">
<span>Romanian Athenaeum</span>
</div>
<div class="landmark-button" id="romanian-athenaeum-button"></div>
</div>
</div>
----------------------------------------------------------
<div class="landmarks-info-wrapper">
<div class="landmark-info" id="arch-of-triumph-info">
<div class="info-landmark section">
<span class="landmark-title">Arch of Triumph</span>
<span class="landmark-coord">44°28′1.99″N 26°4′41.06″E</span>
</div>
</div>
<div class="landmark-info" id="romanian-athenaeum-info">
<div class="info-landmark section">
<span class="landmark-title">The Romanian Athenaeum</span>
<span class="landmark-coord">44.4413°N 26.0973°E</span>
</div>
</div>
Assuming you're not able to modify your HTML markup (in which case with use of CSS classes would be cleaner), a solution to your question would be as shown below:
// Assign same click handler to all buttons
$("#arch-of-triumph-button, #romanian-athenaeum-button, #palace-of-parliament-button")
.click(function() {
// Extract id of clicked button
const id = $(this).attr("id");
// Obtain corresponding info selector from clicked button id by replacing
// last occurrence of "button" pattern with info.
const infoSelector = "#" + id.replace(/button$/gi, "info");
// Add active-info class to selected info element
$(infoSelector).addClass("active-info");
});
Because each .landmark-button looks to be in the same order as its related .landmark-info, you can put both collections into an array, and then when one is clicked, just find the element with the same index in the other array:
const buttons = [...$('.landmark-button')];
const infos = [...$('.landmark-info')];
$(".landmark-button").click(function() {
const i = buttons.indexOf(this);
$(infos[i]).addClass('active-info');
});
This does not rely on IDs at all - feel free to completely remove those from your HTML to declutter, because they don't serve any purpose now that they aren't being used as selectors.
Live snippet:
const buttons = [...$('.landmark-button')];
const infos = [...$('.landmark-info')];
$(".landmark-button").click(function() {
const i = buttons.indexOf(this);
$(infos[i]).addClass('active-info');
});
.active-info {
background-color: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="landmark-wrapper">
<div class="page-content landmark">
<div class="heading span-after">
<span>Arch of Triumph</span>
</div>
<div class="landmark-button" id="arch-of-triumph-button">click</div>
</div>
</div>
<div class="landmark-wrapper">
<div class="page-content landmark">
<div class="heading span-after">
<span>Romanian Athenaeum</span>
</div>
<div class="landmark-button" id="romanian-athenaeum-button">click</div>
</div>
</div>
----------------------------------------------------------
<div class="landmarks-info-wrapper">
<div class="landmark-info" id="arch-of-triumph-info">
<div class="info-landmark section">
<span class="landmark-title">Arch of Triumph</span>
<span class="landmark-coord">44°28′1.99″N 26°4′41.06″E</span>
</div>
</div>
<div class="landmark-info" id="romanian-athenaeum-info">
<div class="info-landmark section">
<span class="landmark-title">The Romanian Athenaeum</span>
<span class="landmark-coord">44.4413°N 26.0973°E</span>
</div>
</div>
Older answer, without knowing the HTML: You can extract the ID of the clicked button, slice off the button part of it, and then select it concatenated with -info:
$(".landmark-button").click(function() {
const infoSel = this.id.slice(0, this.id.length - 6) + 'info';
$(infoSel).addClass('active-info');
});
A much more elegant solution would probably be possible given the HTML, though.

Add JSON item into localStorage

I'm working on an angular task and the goal is to add items to be purchase into localStorage before adding to cart.
I have four different object that users can add, item can be added several time, so the general condition is if object exist on localStorage and user add it other time I should update quantity attribute, if not add new object with new attribute quantity = 1.
here is the service :
addGiftToCard(type) {
let cardParse = JSON.parse(localStorage.getItem('cart')) || []
let index = _.findIndex(cardParse, item => item.type && item.id == type.id)
if (index == -1) {
type.qte = 1
cardParse.push(type)
} else {
cardParse[index].qte += 1
}
localStorage.setItem('cart', JSON.stringify(cardParse))
}
and the function in my component :
addGiftToCart(type) {
let index = this.cartService.addGiftToCard({ type: type })
}
html :
<div class="available-checks" *ngIf="!(types === null)">
<div class="row checks-list">
<div class="col-md-3" *ngFor="let type of types">
<div class="card">
<div class="card-body">
<div class="row">
<div class="col-8 logo-container justify-content-center">
<img class="card-logo" src="../../../assets/images/logo-gold.svg" alt="">
</div>
<div class="col-4 icon-container justify-content-center text-center">
<img [src]=" serverUrl+'/'+type?.image" alt="" style="width: 50px;height: 50px;">
</div>
</div>
<div class="row desc-title-c">
<p class="desc-title">Chèque cadeau</p>
</div>
<div class="row type-c">
<p class="check-type">{{type.type}}</p>
</div>
<div class="offer-container">
<p class="offer">{{type.designation}}</p>
<p class="price">{{type.amount}}€</p>
</div>
<div class="">
<button class="btn btn-footer" (click)="addGiftToCart(type)">Ajouter au panier</button>
</div>
</div>
</div>
</div>
</div>
</div>
The problem I got here is the one object added what ever the item is and only the quantity attribute counter updated and got json format like that :
and If I set type = type.type in the service function It works and I got json like that
I need the json element type do not contain an attribute qty, qty should be outside the object attributes like the first image !
I think you should have used item.type.id instead of item.id like below
let index = _.findIndex(cardParse, item => item.type && item.type.id == type.id)

removing and adding a class based on position within an array Angular

I am creating a blog page using angular 5 where each of the blog posts have the class:
col-md-4
However, what I want is the latest blog post (i.e the first on the page) to have the class of :col-md-12.
The html that I have is as follows:
<div *ngFor="let blog of blogs" class="blog-posts col-md-4">
<div class="card">
<img class="blog-img" (click)="goToBlogDetailsPage(blog.sys.id)"src="{{blog.fields.blogimage.fields.file.url}}" class="rounded" alt="">
<div class="info">
<h3 class="author">{{blog.fields.authorInfo}}</h3>
<h2 (click)="goToBlogDetailsPage(blog.sys.id)" class="title">{{blog.fields.title}}</h2>
<p class="short-desc" > {{blog.fields.desciption}}</p>
<img (click)="goToBlogDetailsPage(blog.sys.id)" class="sml-logo" src="/assets/img/logos/logo_blue.png" alt="">
<!-- <button (click)="goToBlogDetailsPage(blog.sys.id)"class="btn btn-info">Open Blog Post</button> -->
</div>
</div>
</div>
</div>
</div>
I have tried accessing the index of the array[0] however I can not seem to alter the styling on just the first item, any suggestions?
Use index and ternary operator to set the class
<div *ngFor="let blog of blogs; let ind = index" class="blog-posts"
[ngClass]="ind === 0 ? 'col-md-12' : 'col-md-4'" >

Categories

Resources