angular - 如何在 Angular 应用程序的单独页面中显示帖子标题?
问题描述
我已经根据他的索引为每个帖子准备了路由。
您可以在屏幕截图 #2 中看到 URL 是动态的。我需要在打开的页面上显示所选帖子的标题
这是存储库的链接https://github.com/paslavskyi9roman/Freecher
<div
class="post"
*ngFor="let post of posts; let i = index"
[attr.data-index]="i"
>
<a [title]="post.title" [routerLink]="['/post/', i]">
<div class="title">
<h1>{{ post.title }}</h1>
<span>Posted by: {{ post.author }}</span>
</div>
<div class="body">
<p>{{ post.text }}</p>
</div>
</a>
</div>
解决方案
首先在您的 Post 界面中添加 id:
export interface Post {
id: number,
title: string,
text: string,
author: string,
}
然后在你的 mock-post.ts 中添加 id:
export const POSTS: Post[] = [
{id:1, title: 'Post 1', text: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. ', author: 'Nickname'},
...
...
...
{id:8, title: 'Post21', text: 'lorem 3 text', author: 'Nickname'},
]
像这样更改您的 post.component.html:
<div class="post" *ngFor="let post of posts;" [attr.data-index]="post.id">
<a [title]="post.title" [routerLink]="['/post/', post.id]">
<div class="title">
<h1>{{ post.title }}</h1>
<span>Posted by: {{ post.author }}</span>
</div>
<div class="body">
<p>{{ post.text }}</p>
</div>
然后像这样更改您的 view-post.component.ts :
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { POSTS } from 'src/app/mock-posts';
import { Post } from 'src/app/interface-post';
@Component({
selector: 'app-view-post',
templateUrl: './view-post.component.html',
styleUrls: ['./view-post.component.scss']
})
export class ViewPostComponent implements OnInit {
id: any;
post: any;
constructor(private activatedRoute: ActivatedRoute) {
this.activatedRoute.paramMap.subscribe((x: { get: (arg0: string) => any; }) => {
this.id = x.get('id');
});
}
ngOnInit(): void {
this.post = POSTS.find(x=>x.id == this.id);
}
}
最后将其添加到您的 view-post.component.html 中:
<div class="view-post">
<h1>{{post.title}}</h1>
<p>{{ post.text }}</p>
</div>
推荐阅读
- mysql - 添加触发器时,表对数据库是未知的
- opencv - 使用python中的关键点进行复制移动伪造检测
- wordpress - 如何在 WordPress 中添加自定义帖子类型的搜索功能
- javascript - 使用对象文字并使用 lodash 绑定所有方法是一种好习惯吗?
- database - SQL删除日期早于x天的所有行
- visual-studio - Visual Studio 2017 外部 Web 工具设置存储在哪里?
- excel - 如何将一列与包含一些空白单元格的列匹配?
- r - R:将列表列表的列表写入具有名称的文本文件
- ssis - 外部组件在 microsoft sql server Dts 运行时引发了异常
- java - Woodstox 通过 SimpleXML 属性限制 - 如何设置它们?