我已经构建了用户列表,并用来自此源的相关数据填充(https://jsonplaceholder.typicode.com/posts)。我显示了'标题'和'正文'。然后我在每个用户的标题旁边做了“编辑”按钮,所以每当你点击它时,就会打开两个输入字段('title'和'body')。现在我想用上面提到的源中的默认数据填充这两个输入字段。另外,如果有人使用输入更改文本,则应更改数据。我试着这样做,但它没有用。
这是HTML文件:
<div class="forms container">
<form #postForm="ngForm">
<div class="form-group">
<label for="title">Title</label>
<input [(ngModel)]="title"
name="title"
id="title"
type="text"
class="form-control"
>
</div>
<div class="form-group">
<label for="body">Body</label>
<textarea [(ngModel)]="body" id="body" cols="30" rows="10"
class="form-control"
></textarea>
</div>
<button class="btn btn-success">Submit</button>
</form>
</div>
这是我的component.ts文件:
import { Component, OnInit } from '@angular/core';
import { PostService } from 'src/app/shared/posts.service';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-forms',
templateUrl: './forms.component.html',
styleUrls: ['./forms.component.css']
})
export class FormsComponent implements OnInit {
posts: any;
constructor(private postService: PostService ,private route: ActivatedRoute) { }
ngOnInit() {
this.postService.getPosts().subscribe(
(posts: any) => this.posts = posts
);
}
}
这是我的PostService:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class PostService {
constructor(private http: HttpClient) { }
getPosts() {
return this.http.get('https://jsonplaceholder.typicode.com/posts')
}
}
您似乎没有编写任何代码来处理表单?
这段代码:
export class FormsComponent implements OnInit {
posts: any;
constructor(private postService: PostService ,private route: ActivatedRoute) { }
ngOnInit() {
this.postService.getPosts().subscribe(
(posts: any) => this.posts = posts
);
}
}
似乎只是列表组件中代码的副本。
如果您希望表单组件只能使用一个帖子,那么代码只需要检索一个帖子(而不是所有帖子)。
如果您的表单绑定到:
[(ngModel)]="title"
和
[(ngModel)]="body"
您的组件需要公开这些属性。
以下是显示详细信息页面的一些代码示例。您的编辑表单的代码类似:
https://github.com/DeborahK/Angular-GettingStarted/tree/master/APM-Final
要么
您需要在组件中包含名为title
和body
的属性,并为其指定值。这是stackblitz上的示例:https://stackblitz.com/edit/angular-we5mfr