0

I have this in my template file:

<div class="read-one-article">
  <mat-list
    role="list"
    *ngFor="let article of articleService.dataSource.article"
  >
    <mat-list-item role="listitem">
      <h3>{{ article.id }}</h3>
    </mat-list-item>
    <mat-list-item role="listitem">
      <div class="article-title">
        <h3>{{ article.title }}</h3>
        <span class="article-user-id">user: {{ article.user_id }}</span>
      </div>
    </mat-list-item>
    <mat-list-item role="listitem">
      {{ article.content }}
    </mat-list-item>
    <mat-divider></mat-divider>
  </mat-list>
</div>

I need to pass article.id variable to function as atribute in .ts file same component:

export class ReadOneArticleComponent implements OnInit {
  constructor(public articleService: ArticleService) {}

  ngOnInit() {
    this.articleService.readArticle(article.id);
  }
}
Srdjan Milic
  • 328
  • 2
  • 14
  • 1
    Does this answer your question? [Call a function inside ngFor in angular2](https://stackoverflow.com/questions/38787839/call-a-function-inside-ngfor-in-angular2) – ruth Mar 24 '20 at 13:01
  • The above solution is to call a function inside the template for loop. I need opposite functionality, to pass `article.id` value from a template loop to `readArticle()` function as attribute, like this `this.articleService.readArticle(article.id);` Thank you for the comment. – Srdjan Milic Mar 24 '20 at 18:43
  • When I click the read one article from a page where all articles are listed, I get new page rendered with the article/id data `http://localhost:4200/list-articles/1`. The problem is, when I refresh that page data is lost and page became blank(no data). When I hardcode the article id like this `ngOnInit() { this.articleService.readArticle(1); }` it works perfectly. – Srdjan Milic Mar 24 '20 at 19:16

1 Answers1

0

Problem was that route ..list-article/:id after refresh doesn't show article data. The page was blank. The above approach is totally wrong. The solution was ActivatedRoute class from angular router. So, I was refactor my code and that problem was solved.
Here is the working code:

import { Component, OnInit } from "@angular/core";
import { ArticleService } from "../../services/article.service";
import { ActivatedRoute } from "@angular/router";

@Component({
  selector: "app-read-one-article",
  templateUrl: "./read-one-article.component.html",
  styleUrls: ["./read-one-article.component.less"],
})
export class ReadOneArticleComponent implements OnInit {
  id: number;

  constructor(
    public articleService: ArticleService,
    private route: ActivatedRoute
  ) {}

  ngOnInit() {
    this.id = this.route.snapshot.params["id"];
    this.articleService.readArticle(this.id);
  }
}
Srdjan Milic
  • 328
  • 2
  • 14