Reactive Forms

Edit Flights

In this exercise you will implement a Reactive Form to edit Flights.

  1. Create a FlightEditComponent which belongs to the FlightBookingModule:

    ng generate component flight-booking/flight-edit
    
  2. Import the ReactiveFormsModule in the FlightBookingModule.

  3. If no router is used in your Angular App yet, you need to export your Component and use the Component's tag in your AppComponent's Template.

  4. Your FlightEditComponent shall define FormGroup named editForm.

    Show code

    […]
    import {FormGroup} from '@angular/forms';
    
    @Component({[…]})
    export class FlightEditComponent implements OnInit {
    
        editForm: FormGroup = this.getInitialEditForm();
    
        […]
    }
    

  5. Request the FormBuilder via Dependency Injection in the FlightEditComponent.

    Show code

    import {[…], FormBuilder} from '@angular/forms';
    
    @Component({
        […]
    })
    export class FlightEditComponent implements OnInit {
        […]  
        constructor(private fb: FormBuilder) {
        }
        […]
    }
    

  6. Use the FormsBuilder in the new method getInitialEditForm() method to create a FormGroup which represents a Flight and assign it to the editForm property.

    Show code

    
    export class FlightEditComponent implements OnInit {
        editForm: FormGroup = this.getInitialEditForm();
        […]  
        getInitialEditForm(): FormGroup {
            return this.fb.group({
                id:   [1],
                from: [],
                to:   [],
                date: []
            });
        }
        […]
    }
    

  7. Use the code completion feature of your IDE to see which properties and methods are available for the editForm property. Use console.log() to output information like value, valid, touched or dirty.

    Show code

    
    export class FlightEditComponent implements OnInit {
        […] 
        save(): void {
            console.log('value', this.editForm.value);
            console.log('valid', this.editForm.valid);
            console.log('touched', this.editForm.touched);
            console.log('dirty', this.editForm.dirty);
        }
        […]
    }
    

  8. subscribe() to editForm.valueChanges which is of type Observable and log this value to the console as well. You will get notified each time one of the form inputs change.

    Show code

    export class FlightEditComponent implements OnInit {
    […]
        ngOnInit() {
            […]
            this.editForm.valueChanges.subscribe(v => {
                console.log('changes', v);
            });
        }
    […]
    }
    

  9. Open the file flight-edit.component.html and create the necessary HTML markup for your form. The form needs to be connected to your FormGroups by using the property editForm.

    Show code

    <form [formGroup]="editForm">
        <div class="form-group">
            <label>Id:</label>
            <input formControlName="id" class="form-control">
        </div>
    
        <div class="form-group">
            <label>Date:</label>
            <input formControlName="date" class="form-control">
        </div>
    
        <div class="form-group">
            <label>From:</label>
            <input formControlName="from" class="form-control">
        </div>
    
        <div class="form-group">
            <label>To:</label>
            <input formControlName="to" class="form-control">
        </div>
    
        <div class="form-group">
            <button (click)="save()" class="btn btn-default">Save</button>
        </div>
    
    </form>
    

  10. Test your application.

Build-in Validators

Now you will add the Build-in Validators required and minlength to your Reactive Forms implementation.

  1. Open the file flight-edit.component.ts and add those Validators to the FormGroup. minlength shall be set to 3.

    Show code

    […]
    getInitialEditForm(): FormGroup {
        return this.fb.group({
            id:   [1],
            from: [null, [Validators.required, Validators.minLength(3)]],
            to:   [null],
            date: [null]
        });
    }
    […]	
    

  2. Open the file flight-edit.component.html and add the HTML markup to show errors for the FormControl from.

    Show code

    <input formControlName="from">		
    […]          
    errors: {{ editForm.controls['from'].errors | json }}	
    

  3. Use the hasError() method of the FormControl to find out whether the minlength error occurred.

    Show code

    <input formControlName="from" […] >		
    […]
    <div
        class="alert alert-danger"
        *ngIf="editForm.controls['from'].hasError('minlength')">		
        ...minlength...
    </div>