简体   繁体   中英

Select object in a list from previous component Angular

I have a details.component and a list.component . My App is about cars.

You can open up a car in the details component to see it's details. After returning to the list component by pressing the back button (integrated back-button), the car you looked before should be selected/highlighted.

The list component is a large list of all cars. I am using bootstrap. I guess the car from the details component must be overhanded with a service? Or is there a simple solution?

I'm a beginner in angular. I would appreciate any kind of examples. Thank you very much

UPDATE:

list.component

carId$ = this.routerQuery.selectParams<number>('carId').pipe(
    distinctUntilChanged(),
    untilDestroyed(this),
    filter(carId => +carId > 0)
  );

constructor(carService){

this.carId$.subscribe(carid => {
              this.carService.getCarById(+carid);
              console.log(carid)
            })

How can I highlight / select the last viewed car in the html file?

I created a full example stackblitz for you.

I created two components: cars.component and detail.component I created a car.service.ts which is handling selection and emulating retrieving cars, probably by a backend.

I am getting the id from the url to retrieve the data by a backend call.

Here is the stackblitz: Cars selection service example

For this, You can use anchor tag with routerLinkActive and routerLinkActiveOptions attribute. Each of your CarList should be wrapped with anchor element. Change the class-name on click on your element.

Something like this,

<a class="nav-link" routerLink="" routerLinkActive="visited" routerLinkActiveOptions="{exact:true}">Benz</a>

Your css code can be something like this,

.visited{
    color:red;
}

Reference: Change color of selected link in angular 4

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM