Issue
Any object's card that is clicked will print that object's info to the console, but the child view will only display the info from the first object in the array it pulls from. I will include all pages, top down. Picture example near bottom of post.
Relevant part of Grandparent View:
<div class="list">
<app-animal-list-item *ngFor="let item of apiService.items; even as isEven"
[class.rightBorder]="isEven" [item]="item"></app-animal-list-item>
</div>
(Grandparent doesn't have any .ts code pertaining to these children)
Parent View(app-animal-list-item):
<div class="container" (click)="showPage()">
<p id="name">{{ item.attributes.name }}</p>
<img src="{{ item.attributes.pictureThumbnailUrl }}" alt="No Picture Provided">
<p id="distance">{{ item.attributes.distance }} miles</p>
</div>
<app-animal-page [animal]="item"></app-animal-page>
Parent .ts file(app-animal-list-item):
@Input() item: any;
@ViewChild(AnimalPageComponent)
child!: AnimalPageComponent;
constructor() { }
ngOnInit(): void {
}
showPage(){
this.child.toggleDisplay();
}
Child View(app-animal-page):
<div class="hide" id="container">
<img src="{{ animal.attributes.pictureThumbnailUrl }}" alt="No Picture Provided">
<span><p>{{ animal.attributes.name }}</p><p>{{ animal.attributes.ageString }}</p></span>
</div>
Child .ts file(app-animal-page):
@Input() animal: any;
container!:any;
constructor() { }
ngOnInit(): void {
this.container = document.getElementById("container");
}
toggleDisplay() {
console.log(this.animal.attributes.name);
console.log(this.animal.attributes.pictureThumbnailUrl);
this.container.classList.toggle("hide");
}
Pic shows console and display
The first animal's(first object in the array shown in console) picture, in bottom left corner, is displayed when any animal's card is clicked. Yet, the correct animal's info is printed to the console at the time of said click.
Can anyone explain why this is happening? Your help is much appreciated.
Solution
document.getElementById("container")
is pulling the first element with that ID on the page. ID's should be unique, but if you are using this component multiple times then they are all going to have that same "container" ID.
I'd recommend using a variable to set the class instead of toggling it with classList
<div [class.hide]="hidden" id="container">
<img src="{{ animal.attributes.pictureThumbnailUrl }}" alt="No Picture Provided">
<span><p>{{ animal.attributes.name }}</p><p>{{ animal.attributes.ageString }}</p></span>
</div>
@Input() animal: any;
container!:any;
hidden: boolean = false;
constructor() { }
ngOnInit(): void {
this.container = document.getElementById("container");
}
toggleDisplay() {
console.log(this.animal.attributes.name);
console.log(this.animal.attributes.pictureThumbnailUrl);
this.hidden = !this.hidden;
}
Answered By - abney317
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.