考虑一个简单的增删改查场景。我在 app.component.html
中有很多输入字段和按钮。当我按下 app.component.html
中的按钮时,它会将 html 字段值发送到“other.component.ts”组件,并将结果显示回 app.component.html
处理后(如加法、减法或其他)。
这里是app.component.html
<a routerLink="posts/">Show Posts</a>
<input type="number" [(ngModel)]="get-one-post-id">
<a routerLink="/post-by-id">Show One Posts</a>
<router-outlet>
</router-outlet>
post-by-id-component.ts
import { Component, OnInit } from '@angular/core';
import { DataService } from '../data.service';
import { Observable } from 'rxjs';
@Component({
selector: 'app-post-by-id',
templateUrl: './post-by-id.component.html',
styleUrls: ['./post-by-id.component.css']
})
export class PostByIdComponent implements OnInit {
posts: object;
constructor(private dataService: DataService) { }
ngOnInit(): void {
// const id = ??
this.GetPost(1);
}
async GetPost(id: number)
{
const response = await this.dataService.Get_A_Post(id);
const dataService = await response.json();
this.posts = dataService;
}
}
post-by-id-component.html
<div *ngFor="let post of posts">
<h3>{{post.title}}</h3>
<p>{{post.body}}</p>
</div>
我只想从 get-one-post-id 字段中获取值,从 app.component.html 到 post-by-id- component.ts [我评论的地方//const id = ??]。但我找不到导入它的方法。
最佳答案
在 Angular 组件之间共享数据有 4 种不同的方式:
父对子:通过输入共享数据
子级到父级:通过 ViewChild 共享数据
- 子级到父级:通过 Output() 和 EventEmitter 共享数据
- 不相关的组件:与服务共享数据
您可以阅读this有用的文章来了解它是如何工作的。
关于javascript - Angular:如何从一个组件前端(app.component.html)到另一组件后端(other.component.ts)获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61058498/