角反应形式,添加和删除字段? [英] Angular reactive forms, adding and removing fields?

查看:24
本文介绍了角反应形式,添加和删除字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 angular 5 中构建 crud 应用程序时,我遇到了一个问题,如何使用相同的表单构建器,但根据我的需要更改我获得的表单控件,通过表单添加或更新用户...

这是一些简单的代码,我会尽量不把事情复杂化,因为我有很多属性的大表单......

所以在我的 app.component.html 中有表单

 
<div class="form-group"><label for="firstName" class="control-label必填">名字</label><input type="text" id="firstName" class="form-control"formControlName="firstName">

<div class="form-group"><label for="lastName" class="control-label必填">姓氏</label><input type="text" id="lastName" class="form-control"formControlName="lastName">

在我的 app.component.ts

在我的构造函数中我有

 this.form = this.formBuilder.group({firstName: ['', [Validators.required, Validators.minLength(2),Validators.pattern(/^[a-zA-Z]+$/)]],lastName: ['', [Validators.required, Validators.minLength(2),Validators.pattern(/^[a-zA-Z]+$/)]],});

和用于提交表单的 save() 函数

 save() {让 formModel = this.form.value;formModel.id = this.Id;如果(this.Id == null){this._usermanagementservice.addEmployee(formModel).subscribe(() => {//重新加载员工表的函数this.LoadAllEmployees();});}别的 {this._usermanagementservice.updateEmployee(this.Id, formModel).subscribe(() => {this.LoadAllEmployees();});}}

请注意,一切正常,我没有包含其他字段,但问题是,如何在添加用户时仅包含名字字段的表单,并且只有姓氏用于更新?(为了简化事情,我使用了这个例子的名字和姓氏)

谢谢,如果您需要更多信息,我很乐意提供附言.英语是我的第二语言,所以字段、表格等术语肯定是不正确的,希望你能明白

解决方案

首先你可以根据你的选择创建一组模板.我们可以在模板中使用 *ngIf 来隐藏和显示表单中的元素组.然后使用 formBuilder 创建表单的表单实例,每次只传递那些启用的表单控件的对象.

<块引用>

模板

<label for="name">名字:</label><input type="text" formControlName="fname"占位符=输入名称"><br/><br/><div *ngIf="lNameEmail1"><label for="name">姓氏:</label><input type="text" formControlName="lname"占位符=输入名称"><br/><br/><label for="email">电子邮件:</label><input type="email" formControlName="email"placeholder="输入电子邮件">

<div *ngIf="lNameEmail2"><label for="name">Last Name2:</label><input type="text" formControlName="lname2"占位符=输入名称"><br/><br/><label for="email">Email2:</label><input type="email" formControlName="email2"placeholder="输入电子邮件">

<br/><br/><button type="submit" [disabled]="!myForm.valid">提交<button type="submit" (click)='formGrp1()'>表单 1<button type="submit" (click)='formGrp2()'>表单 2</表单>

<块引用>

角度类

导出类 AppComponent 实现 AfterViewInit {公共 myForm:FormGroup;lNameEmail1 = false;lNameEmail2 = false;myFormProperty1 = {"fname": new FormControl("", Validators.required)};myFormProperty2 = {"fname": new FormControl("", Validators.required),"lname": new FormControl("", Validators.required),"email": new FormControl("")};myFormProperty3 = {"fname": new FormControl("", Validators.required),"lname2": new FormControl("", Validators.required),"email2": new FormControl("")};构造函数(公共FB:FormBuilder){this.myForm = this.fb.group(this.myFormProperty1);}formGrp1(){alert('Form 1 启用')this.lNameEmail1 = true;this.lNameEmail2 = false;this.myForm = this.fb.group(this.myFormProperty2);this.myForm.valueChanges.subscribe(data =>console.log('表单对象 ====' + JSON.stringify(data)));}formGrp2(){alert('表格 2 启用')this.lNameEmail1 = false;this.lNameEmail2 = true;this.myForm = this.fb.group(this.myFormProperty3);this.myForm.valueChanges.subscribe(data =>console.log('表单对象 ====' + JSON.stringify(data)));}提交(){console.log('表单提交值=='+ JSON.stringify(this.myForm.value));}}

while building crud app in angular 5 I've come across with a question, how can I use the same form builder but change what form controls I get depending on what I want, adding or updating users thru form...

Here's some simple code, I will try not to complicate things, since I have pretty big form with lot of attributes...

So in my app.component.html i have form

         <form class="form-horizontal" [formGroup]="form" #myForm="ngForm" 
          (ngSubmit)="save()"> 
                <div class="form-group">
                    <label for="firstName" class="control-label 
                  required">First name</label>
                    <input type="text" id="firstName" class="form-control" 
             formControlName="firstName">


                </div>

                <div class="form-group">
                    <label for="lastName" class="control-label 
            required">Last name</label>
                    <input type="text" id="lastName" class="form-control" 
            formControlName="lastName"> 
                </div>

and in my app.component.ts

in my constructor i have

    this.form = this.formBuilder.group({ 
        firstName: ['', [Validators.required, Validators.minLength(2), 
   Validators.pattern(/^[a-zA-Z]+$/)]],
        lastName: ['', [Validators.required, Validators.minLength(2), 
   Validators.pattern(/^[a-zA-Z]+$/)]],

    });

and save() function for submiting the form

    save() {
    let formModel = this.form.value;
    formModel.id = this.Id;

    if (this.Id == null) { 
        this._usermanagementservice.addEmployee(formModel).subscribe(() => {

           //function that reloads table with employees
            this.LoadAllEmployees();
        });
    }
    else {
        this._usermanagementservice.updateEmployee(this.Id, formModel).subscribe(() => {
            this.LoadAllEmployees();
        });
    }
}

Noted that everything works, I've not included other fields, but here's the question, how can I include only form for first name field on adding user, and have ONLY last name for updating? (to simplfy things, I'm using this example first and last name)

Thanks, If you need more info, I'll gladly provide it Ps. english is my secondary language, so terms like fields, forms and etc. are for sure incorrect, hopefully you'll get the point

解决方案

First you can create group of template basis of your option. We can use *ngIf in template to hide and show group of elements in form. Then use formBuilder to create form instance of form each time pass only object of those form controls which are enable.

Template

<form [formGroup]="myForm" (ngSubmit)="onSubmit()">
<label for="name">First Name:</label>
<input type="text" formControlName="fname"
placeholder="Enter name">
<br /><br />
<div *ngIf="lNameEmail1">
<label for="name">Last Name:</label>
<input type="text" formControlName="lname"
placeholder="Enter name">
<br /><br />
<label for="email">Email:</label>
<input type="email" formControlName="email"
placeholder="Enter email">
</div>
<div *ngIf="lNameEmail2">
<label for="name">Last Name2:</label>
<input type="text" formControlName="lname2"
placeholder="Enter name">

<br /><br />

<label for="email">Email2:</label>
<input type="email" formControlName="email2"
placeholder="Enter email">
</div>
<br /><br />
<button type="submit" [disabled]="!myForm.valid">Submit
</button>
<button type="submit" (click)='formGrp1()'> Form 1</button>
<button type="submit" (click)='formGrp2()'> Form 2</button>
</form> 

Angular class

export class AppComponent implements AfterViewInit {
        public myForm: FormGroup;
        lNameEmail1 = false;
        lNameEmail2 = false;
        myFormProperty1 = {
        "fname": new FormControl("", Validators.required)
        };

        myFormProperty2 = {
        "fname": new FormControl("", Validators.required),
        "lname": new FormControl("", Validators.required),
        "email": new FormControl("")

        };
        myFormProperty3 = {
        "fname": new FormControl("", Validators.required),
        "lname2": new FormControl("", Validators.required),
        "email2": new FormControl("")

        };

        constructor(public fb: FormBuilder) {
        this.myForm = this.fb.group(this.myFormProperty1);
        }


        formGrp1(){
        alert('Form 1 enable')

        this.lNameEmail1 = true;
        this.lNameEmail2 = false;

        this.myForm = this.fb.group(this.myFormProperty2);


        this.myForm.valueChanges.subscribe(data =>
        console.log('form object ====' + JSON.stringify(data)
        )); 
        }
        formGrp2(){
        alert('Form 2 enable')
        this.lNameEmail1 = false;
        this.lNameEmail2 = true;

        this.myForm = this.fb.group(this.myFormProperty3);

        this.myForm.valueChanges.subscribe(data =>
        console.log('form object ====' + JSON.stringify(data)
        )); 

        }
        onSubmit() {
        console.log('Form submitted Value=='+ JSON.stringify(this.myForm.value));
        }

    }

这篇关于角反应形式,添加和删除字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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