Greetings to all =) I've recently delved into Angular 9 and I'm really enjoying the component-based approach. To sharpen my skills in property and event binding, I embarked on a project involving building a deck with two lists. English isn't my first language, but I'll do my best to explain clearly.
IMPORTANT: Since I'm keen on mastering this tool, could you please provide detailed explanations in your responses? If you have hints or solutions, I'm open to exploring them independently for learning purposes.
GOAL:
The aim is to have two lists (CardlistComponent and DecklistComponent) where clicking on an item in CardListComponent (or DecklistComponent) removes it from that list and adds it to the other list.
COMPONENTS :
- DeckbuilderComponent containing the two other components (the two lists)
- CardlistComponent (the first list)
- DecklistComponent (the second list)
ISSUE:
I can successfully remove an element from CardlistComponent, but I'm struggling to add the same element to DecklistComponent. I believe the problem lies in how I handle arrays in JavaScript.
DeckbuilderComponent (HTML) (Parent component)
<app-cardlist></app-cardlist>
<app-decklist
(cardAdded)="onCardAdded($event)">
</app-decklist>
*DeckbuilderComponent (TS)* (Parent component) The issue might be related here as I've duplicated the logic of adding an item in the parent AND in DecklistComponent.
@Output() cardAdded = new EventEmitter<{name: string}>();
decklist: Card[] = [
new Card('CardC'),
new Card('CardD')
]
onCardAdded(element : HTMLLIElement){
this.decklist.push({
name: element.textContent
})
}
CardlistComponent
@Output() cardRemoved = new EventEmitter<{cardName: string}>();
cardlist: Card[] = [
new Card('CardA'),
new Card('CardB')
]
removeCard(indexCard: number, element: HTMLLIElement){
this.cardlist.splice(indexCard, 1)
this.cardRemoved.emit({
cardName: element.textContent
});
DecklistComponent - this list should receive the element removed from the first list
@Input() cardName: {name: string};
decklist: Card[] = [
new Card('CardC'),
new Card('CardD')
]
onCardAdded(element : HTMLLIElement){
this.decklist.push({
name: element.textContent
})
}
Here's the HTML code for my two components just in case.
DecklistComponent (HTML)
<div class="container">
<div class="col-xs-12">
<ul class="list-group">
<li
*ngFor="let card of decklist; let indexCard=index"
class="list-group-item"
#cardName
>
<a href="#" class="list-group-item list-group-item-action" >{{ card.name }}</a>
</li>
</ul>
</div>
CardlistComponent (HTML)
<div class="container">
<div class="col-xs-12">
<ul class="list-group">
<li *ngFor="let card of cardlist; let indexCard=index" class="list-group-item">
<a href="#"
(click)="removeCard(indexCard, card)"
class="list-group-item list-group-item-action">{{ card.name }}</a>
</li>
</ul>
</div>
If there's anything else important that I missed mentioning, please feel free to share, and may your day be filled with enthusiastic coding =D