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

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

问题描述

在用角度5构建Crud应用程序时,我遇到了一个问题,如何使用相同的表单生成器,但要根据自己的需要更改获取的表单控件,通过表单添加或更新用户...

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...

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

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>

以及在我的app.component.ts

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]+$/)]],

    });

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

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

推荐答案

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

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.

模板

<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> 

角类

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天全站免登陆