Search code examples
angularangular7

How to pass id from .html to .ts in angular?


Basically how the title states, how can I pass an id of an item so when accessing the page I only have that item shown, currently I'm at this stage where I'm stuck in getting the id..

In the .html:

<button routerLink='/items/{{item.id}}'>List item</button>

In the component:

itemArray: GetItems[] = [];    

constructor(){
    item: GetItems[] => {
      this.itemArray.find(item => item.id === id);
    }
}

Update 1: //Error AnonymousSubject

id: Observable<string>;

constructor(route: ActivatedRoute){
  this.id = route.params.pipe(pluck('id'));
  console.log(this.id);

}

Solution

  • You will be able to get the id like this :

    <a [routerLink]="['/items', item.id]">{{ item.id }}</a>
    
    id$: Observable<string>; // This is an observable
    
    constructor(private route: ActivatedRoute) {}
    
    ngOnInit(route: ActivatedRoute) {
      this.id$ = this.route.params.pipe(pluck('id');
      this.id$.subscribe(console.log);
    }
    

    Another method :

    id: string;
    
    constructor(private route: ActivatedRoute) {}
    
    ngOnInit() {
      this.id = this.route.snapshot.paramMap.get('id');
    }
    

    Visit Activated Route and Activated Route in action.