I'm trying to show the first element returned of the list before the user do a selection on the button. For now when you land for first time in the page nothing is selected but I want the first object is selected by defaut. My HTML is :
<div >
<div >
<ul>
<li *ngFor="let destination of destinations">
<button
type="button"
[class.active]="destination == selectedDestination"
(click)="onSelect(destination)"
>
{{ destination.name }}
</button>
</li>
</ul>
</div><div *ngIf="selectedDestination">
<h1>{{ selectedDestination.name }}</h1>
<p >
{{ selectedDestination.description }}
</p>
</div>
and the TS is:
export class DestinationComponent implements OnInit {
destinations: Destinations[] = [];
constructor(private destinationsService: DestinationsService) {}
getDestinations(): void {
this.destinationsService
.getDestinations()
.subscribe((destinations) => (this.destinations = destinations));
}
selectedDestination = this.destinations[0];
onSelect(destination: Destinations): void {
this.selectedDestination = destination;
}
ngOnInit(): void {
this.getDestinations();
}
}
CodePudding user response:
I would just assign it when you get the data
getDestinations(): void {
this.destinationsService
.getDestinations()
.subscribe((destinations) => {
this.destinations = destinations;
this.selectedDestination = destinations[0];
})
}