angular - 使用模板驱动的 Angular 6 中创建和编辑数据的相同表单
问题描述
有2个组件。在DashboardComponent
有一个已创建表单的列表中CreateFormComponent
,我需要对正在显示的已创建表单执行添加和编辑操作DashboardComponent
。两种操作都将使用相同的形式。我可以根据特定 ID 从 导航DashboardComponent
到 ,CreateFormComponent
但无法对其执行编辑操作。代码:dashboard.html
<tr
*ngFor="let user of users"
style="text-align: center;">
<button
mat-mini-fab
style="background: white !important;color:black !important;outline:none;"
[routerLink]="['/Create_form',user.id]">
<!--<i class="fa fa-edit" aria-hidden="true"></i>-->
Edit
</button>
</tr>
Create_Form:
<form
#spfForm="ngForm"
(ngSubmit)="createspf(spfForm.value)"
ngNativeValidate>
<mat-form-field style="margin-top:-6%;">
<mat-select
[(ngModel)]="Priority"
name="Priority"
placeholder="Priority">
<mat-option value="High">
High
</mat-option>
<mat-option value="Medium">
Medium
</mat-option>
<mat-option value="Low">
Low
</mat-option>
</mat-select>
</mat-form-field>
</form>
Create_form.component.ts:
createspf(value) {
this.userservice.spf(value).subscribe((res: Response) => [
this.IsAdded = true,
console.log(this.confirmationString)
]);
}
解决方案
由于您并没有真正提供 StackBlitz,而且我没有时间为您创建一个完整的 Form Stackblitz,所以我建议您这样做:
在你的CreateFormComponent
,当在 中时ngOnInit()
,初始化一个 ReactiveForm,要么使用 a ,要么通过使用andFormBuilder
手动创建一个。FormGroup
FormControls
也注入ActivatedRoute
这个组件并订阅activatedRouterInstance
's params
BehaviorSubject
。如果有任何id
来自那里的信息,请通过该 id 获取项目的详细信息,并通过调用setValue
或填充您创建的表单patchValue
。
在 Create 的情况下,由于参数中没有任何 id,用户只会看到一个空表单。但是在编辑的情况下,由于表单的值将被实现,用户将看到表单填充了实现的数据。
希望这有一定的意义,并帮助你。
推荐阅读
- google-apps-script - 如何使用 Apps 脚本在 BigQuery 中运行查询并将结果保存在表中?
- php - 尝试在 laravel 中的表或其关系中搜索
- asp.net-core - .Net Core 5.0 - 在注册时向用户添加角色
- lua - Lua/love2d - 游戏的资产文件夹路径
- cookies - 管理从其他服务器 next.js 接收到的服务器中的 cookie
- javascript - 如何在一个元素上使用“click”和“dbclick”事件?
- keras - NameError: name 'Model is not defined' - 如何解决这个问题?
- javascript - 从Javascript中的HTML字符串中提取数据
- vaadin - 在一个静态 HTML 中导入两个 Vaadin 嵌入
- c++ - c++ map 和 unordered_map 模板参数:使用 c++20 概念检查常见行为