Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Angular showing first element of array by default in div before selection

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 class="details">
<div class="selector">
  <ul>
    <li *ngFor="let destination of destinations">
      <button
        type="button"
        [class.active]="destination == selectedDestination"
        (click)="onSelect(destination)"
      >
        {{ destination.name }}
      </button>
    </li>
  </ul>
</div><div class="detailsSelected" *ngIf="selectedDestination">
  <h1>{{ selectedDestination.name }}</h1>
  <p class="desription">
    {{ 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();
  }
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I would just assign it when you get the data

getDestinations(): void {
    this.destinationsService
      .getDestinations()
      .subscribe((destinations) => {
        this.destinations = destinations;
        this.selectedDestination = destinations[0];
      })
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading