用于创建和编辑数据 Angular4 的相同形式 [英] Same form for creating and editing data Angular4

查看:17
本文介绍了用于创建和编辑数据 Angular4 的相同形式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个带有两个绑定输入字段的表单.目标是创建相同的表单来编辑和创建数据.这已经完成,但我很确定可以有更好的方法来做到这一点(比如使用 AbstractControl 功能).我也在这里错过了一个修复 - 如果 clickEdit() 被点击需要使用用户想要编辑的对象更新表单值.感谢您的帮助,特别是关于 AbstractControlNgModel..

的解释

<form (ngSubmit)="clicked ? onEditSubmit($event) : onRegisterSubmit($event)" [formGroup] = "form"><div class="form-group"><label>全名</label><input type="text" [(ngModel)]="fullname" formControlName="fullname" class="form-control" >

<div class="form-group"><label>用户名</label><input type="text" [(ngModel)]="username" formControlName="username" class="form-control" >

<div class="form-group"><label>电子邮件</label><input type="text" [(ngModel)]="email" formControlName="email" class="form-control" >

<div class="form-group"><label>密码</label><input type="password" [(ngModel)]="password" formControlName="password" class="form-control">

<button type="submit" class="btn btn-primary" [disabled]="!form.valid">提交</button></表单>

<br><br><table border="2" class="table table-striped"><tr><th>全名</th><th>用户名</th><th>电子邮件</th><th>密码</th><th>删除</th><th>编辑</th></tr><div >

<tr *ngFor="let user of userDetails; index as i"><td>{{user.fullname}}</td><td>{{user.username}}</td><td>{{user.email}}</td><td>{{user.password}}</td><td><button (click)="userDelete()">X</button></td><td><button (click)="clickEdit(i)">编辑</button></td></tr>

import { Component } from '@angular/core';从'firebase'导入{ initializeApp,数据库};从@angular/forms"导入 { FormControl, FormGroup, Validators };@成分({选择器:'app-root',templateUrl: './app.component.html',styleUrls: ['./app.component.css'],})导出类 AppComponent {全名:字符串;用户名:字符串;电子邮件:字符串;密码:字符串;点击=假;用户详细信息:数组<对象>;形式;ngOnInit() {this.userDetails=[];this.form = new FormGroup({全名 : new FormControl("", Validators.required),用户名 : new FormControl("", Validators.required),电子邮件 : new FormControl("", Validators.required),密码:new FormControl("", Validators.required)});}onRegisterSubmit(e){让用户 = {全名 : this.fullname ,用户名:this.username,电子邮件 : this.email ,密码:this.password}this.userDetails.push(user);this.clearInputFields(e);}编辑索引 = 空;点击编辑(i){this.clicked = !this.clicked;this.editIndex = i;}onEditSubmit(e) {让编辑用户 = {全名 : this.fullname ,用户名:this.username,电子邮件 : this.email ,密码:this.password}this.userDetails[this.editIndex] = editUser;this.clearInputFields(e);this.clicked = !this.clicked;}clearInputFields(e){let all = e.target.querySelectorAll('input');Object.keys(all).forEach(key => {console.log(all[key].value = '');});}}

解决方案

我会对您的表单进行一些更改.ngModel 在这里完全是多余的,因为您使用的是反应式表单.改用它并删除所有 ngModel.您从表单中获取的对象与您的 user 匹配,因此您可以做的就是将该值按原样推送到数组.

所以你的模板应该看起来像这样(缩短,作为其余的代码):

<input type="text" formControlName="username" class="form-control" ><input type="submit" class="btn btn-primary" value="Submit" [disabled]="!form.valid"></表单>

在这种情况下我在表单的构建中使用了一个隐藏字段,它也被排除在表单对象之外,因为它是disabled.这对我们来说是一个帮手,所以我们可以区分这是一个新的 user,还是我们正在编辑一个 user.该值包含数组中 user 的索引.所以如果那个值存在,我们知道更新数组中的对象,如果这个值不存在,让我们把用户推送到数组中.

这可以通过多种方式解决,但以上只是一种选择.

this.form = this.fb.group({索引:[{值:空,禁用:真}]用户名 : ['', Validators.required],电子邮件:['',Validators.required],});

所以根据上面的内容,我们可以修改onRegisterSubmit如下:

onRegisterSubmit(form) {//由于字段被禁用,我们需要使用'getRawValue'让 index = form.getRawValue().index如果(索引!= null){this.userDetails[index] = form.value} 别的 {this.userDetails.push(form.value)}this.form.reset()//将表单重置为空}

当我们想编辑一个用户时,我们在模板中传递索引和用户

<tr *ngFor="let user of userDetails; let i = index"><td>{{user.username}}</td><td>{{user.email}}</td><td><button (click)="userEdit(user, i)">Edit</button></td></tr>

然后我们使用 setValue(或 patchValue)输入具有现有值的字段:

userEdit(user, i) {this.form.setValue({指数:我,用户名:user.username,电子邮件:user.email})}

应该可以!所以现在我们可以看到我们可以简化您的代码并摆脱一些不必要的东西!:)

Here is a form with two way-binded input fields. The goal was to create the same form to edit and create data. That was accomplished, but I am pretty sure that there could be a better way to do this (like using AbstractControl features). I also miss one fix here - if clickEdit() being clicked need to update form values with that object which user wants to edit. Thanks for any help and especially explanations about AbstractControl and NgModel..

<div>
<form (ngSubmit)="clicked ? onEditSubmit($event) : onRegisterSubmit($event)" [formGroup] = "form">
  <div class="form-group">
    <label>Full Name</label>
    <input type="text" [(ngModel)]="fullname" formControlName="fullname" class="form-control" >

  </div>
  <div class="form-group">
    <label>Username</label>
    <input type="text" [(ngModel)]="username" formControlName="username" class="form-control" >
  </div>
  <div class="form-group">
    <label>Email</label>
    <input type="text" [(ngModel)]="email" formControlName="email" class="form-control" >
  </div>
  <div class="form-group">
    <label>Password</label>
    <input type="password" [(ngModel)]="password" formControlName="password" class="form-control">
  </div>
  <button type="submit" class="btn btn-primary" [disabled]="!form.valid"> Submit </button>
</form>
</div>

<br>
<br>

<table  border="2" class="table table-striped">
<tr>
  <th>Full Name</th>
  <th>Username</th>
  <th>Email</th>
  <th>Password</th>
  <th>Delete</th>
  <th>Edit</th>
</tr>
<div > </div>
<tr *ngFor="let user of userDetails; index as i">
  <td>{{user.fullname}}</td>
  <td>{{user.username}}</td>
  <td>{{user.email}}</td>
  <td>{{user.password}}</td>
  <td><button (click)="userDelete()">X</button></td>
  <td><button (click)="clickEdit(i)">Edit</button></td>
</tr>
</table>

And

import { Component } from '@angular/core';
import { initializeApp, database } from 'firebase';
import { FormControl, FormGroup, Validators } from '@angular/forms';


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {

  fullname : string;
  username : string;
  email : string;
  password : string;

  clicked = false;

  userDetails:Array<object>;

  form;

  ngOnInit() {
   this.userDetails=[];
    this.form = new FormGroup({
      fullname : new FormControl("", Validators.required),
      username : new FormControl("", Validators.required),
      email : new FormControl("", Validators.required),
      password : new FormControl("", Validators.required)
    });
  }

  onRegisterSubmit(e){
    let user = {
      fullname : this.fullname ,
      username : this.username,
      email : this.email ,
      password : this.password
    }
     this.userDetails.push(user);
     this.clearInputFields(e);
   }

   editIndex = null;

  clickEdit(i){
    this.clicked = !this.clicked;
    this.editIndex = i;
  }

  onEditSubmit(e) {
    let editUser = {
      fullname : this.fullname ,
      username : this.username,
      email : this.email ,
      password : this.password
    }
    this.userDetails[this.editIndex] = editUser;
    this.clearInputFields(e);  
    this.clicked = !this.clicked;  
  }

  clearInputFields(e){
   let all = e.target.querySelectorAll('input');
    Object.keys(all).forEach(key => {
        console.log(all[key].value = '');   
    });    
  }
}

解决方案

I would make quite a few changes to your form. ngModel is totally redundant here as you are using a reactive form. Utilize that instead and remove all ngModel's. The object you are getting from the form, is matching your user, so what you can do, is just push that value as is to the array.

So your template should look something like this (shortened, as the rest of code):

<form (ngSubmit)="onRegisterSubmit(form)" [formGroup] = "form">
  <input type="text" formControlName="username" class="form-control" >
  <input type="submit" class="btn btn-primary" value="Submit" [disabled]="!form.valid">
</form>

In the build of the form I have in this case used a hidden field, that is also excluded from the form object as it is disabled. This is a helper for us, so we can differentiate if this is a new user, or if we are editing a user. The value holds the index of the user from your array. So if that value exists, we know to update the object in the array, if the value does not exist, let's push the user to the array.

This could be solved by numerous ways, but above is one option.

this.form = this.fb.group({
  index: [{value: null, disabled:true}]
  username : ['', Validators.required],
  email : ['', Validators.required],
});

So according to the above, we can modify the onRegisterSubmit to look like the following:

onRegisterSubmit(form) {
  // since field is disabled, we need to use 'getRawValue'
  let index = form.getRawValue().index
  if(index != null) {
    this.userDetails[index] = form.value
  } else {
    this.userDetails.push(form.value)      
  }
  this.form.reset() // reset form to empty
}

When we want to edit a user, we pass the index and the user in template

<tr *ngFor="let user of userDetails; let i = index">
  <td>{{user.username}}</td>
  <td>{{user.email}}</td>
  <td><button (click)="userEdit(user, i)">Edit</button></td>
</tr>

And then we use setValue (or patchValue) to enter the fields with the existing values:

userEdit(user, i) {
  this.form.setValue({
    index: i,
    username: user.username,
    email: user.email
  })
}

That should do it! So now we can see how much we could simplify your code and get rid of some unnecessary things! :)

这篇关于用于创建和编辑数据 Angular4 的相同形式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆