Same form for creating and editing data Angular4

后端 未结 2 730
我寻月下人不归
我寻月下人不归 2020-12-15 11:43

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 b

2条回答
  •  猫巷女王i
    2020-12-15 11:57

    Dummy Forms

    Creating Form that are reusable.

    Folder Structure

    Usage

    User Form Component

    @Input() formData;
    @Output() onSubmit = new EventEmitter();
    @Output() onCancel = new EventEmitter();
    
    ngOnInit(){
        this.form = this.fb.group({
          username : ['', Validators.required]
        });
    
        // Edit Mode will have formData.
        if(this.formData){
            this.form.patchValue(this.formData)
        }
    }
    
    submit(){
       if(this.form.valid){
           this.onSubmit.emit(this.form.value)
       }
    }
    
    cancel(){
      this.onCancel.emit();
    }
    
    

    Add User Component

    
    
    
    addUser(data){
       // Call Http Service to save data
    }
    
    cancel(){
       // navigate to different route or something else
    }
    

    Edit User Component

    
    
    
    ngOnInit(){
       this.formData = //fetch data from server 
    }
    
    updateUser(data){
       // Call Http Service to save data
    }
    
    cancel(){
       // navigate to different route or something else
    }
    

    Pros

    1. Single Component for single use
    2. Can reuse the dummy forms anywhere throughout the application.
    3. Easy to maintain and extend the form

    Cons

    1. For each page you will have 3 components ( add, edit, form).

提交回复
热议问题