Angular reactive forms, adding and removing fields?

前端 未结 4 967
孤街浪徒
孤街浪徒 2021-02-14 10:27

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

4条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-14 11:02

    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









    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));
            }
    
        }
    

提交回复
热议问题