skip to Main Content

I am making a simple Angular app using twitter-bootstrap and jquery to display the data of Employees. 4 data are hardcoded and is displayed in the table as in the image attached to it. I have added “Add Employee” button which pops up the Modal box which contains form to add the employees information. I have used the Validation as well but it submits empty data too.

This is the initial page after i run the app

The error message shows but blank data can be submitted!

This is the table after submtting blank data from the Modal

Here are the components:

employee-data.component.html

<div class="container">
<table class="table table-bordered table-condensed table-responsive">
    <thead class="thead-inverse">
        <tr>
            <td>Id</td>
            <td>Name</td>
            <td>Address</td>
            <td>Gender</td>
            <td>Company</td>
            <td>Action</td>
        </tr>
    </thead>

    <tbody>
        <tr *ngFor="let employee of employees; let i= index;">
            <td>
                <input 
                    class="form-control"
                    type="number" 
                    min="1" [(ngModel)]="employee.id" 
                    [disabled]="!employee.isEditable">
            </td>
            <td>
                <input 
                    type="text"
                    class="form-control"
                    [(ngModel)]="employee.name" 
                    [disabled]="!employee.isEditable"
                    >
            </td>
            <td>
                <input 
                    type="text" 
                    class="form-control"
                    [(ngModel)]="employee.address" 
                    [disabled]="!employee.isEditable"
                    >
            </td>
            <td>
                <input 
                    type="text" 
                    class="form-control"
                    [(ngModel)]="employee.gender" 
                    [disabled]="!employee.isEditable"
                    >
            </td>
            <td>
                <input 
                    type="text" 
                    class="form-control" 
                    [(ngModel)]="employee.company" 
                    [disabled]="!employee.isEditable"
                    >
            </td>
            <td>
                <div>
                    <!-- <button (click)="editEmployee(i)">Edit</button> -->
                    <button 
                        class="btn btn-warning"
                        (click)="employee.isEditable=!employee.isEditable"
                        *ngIf="!employee.isEditable" >
                        Edit
                    </button>
                    <button 
                        class="btn btn-warning"
                        (click)="employee.isEditable=!employee.isEditable"
                        *ngIf="employee.isEditable" >
                        Save
                    </button>
                    <button 
                        class="btn btn-danger"
                        (click)="deleteEmployee(i)">
                        Delete
                    </button>
                </div>
            </td>
        </tr>
    </tbody>
</table>

<!-- Trigger the modal with a button -->
<button 
    type="button" 
    class="btn btn-success btn-md" 
    data-toggle="modal" 
    data-target="#myModal">
        Add Employee
</button>

<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
    <div class="modal-dialog">

        <!-- Modal content-->
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">&times;</button>
                <h4 class="modal-title">Add Employee</h4>
            </div>

            <!-- Modal Body -->
            <div class="modal-body">
                <form  [formGroup]="userForm" (ngSubmit)="addRow()">
                    <div class="form-group">
                        <label>Id</label>
                        <div>
                            <input 
                                type="number" class="form-control" 
                                formControlName="ModalId" name="id"
                                [(ngModel)]="id"
                                min="1" required />
                            <div 
                                class="alert alert-danger"
                                *ngIf="!userForm.controls['ModalId'].valid && userForm.controls['ModalId'].touched">
                                    Error!
                            </div>
                        </div>
                    </div>

                    <div class="form-group">
                        <label>Name</label>
                            <div>
                                <input 
                                    type="text" class="form-control"
                                    formControlName="ModalName" name="name"
                                    [(ngModel)]="name" required />
                            </div>
                            <div 
                                class="alert alert-danger"
                                *ngIf="!userForm.controls['ModalName'].valid && userForm.controls['ModalName'].touched">
                                Error!
                            </div>
                    </div>

                    <div class="form-group">
                        <label>Address</label>
                        <div>
                            <input 
                                type="text" class="form-control" 
                                formControlName="ModalAddress" name="address"
                                [(ngModel)]="address" required />
                            <div 
                                class="alert alert-danger"
                                *ngIf="!userForm.controls['ModalAddress'].valid && userForm.controls['ModalAddress'].touched">
                                    Error!
                            </div>

                        </div>
                    </div>

                    <div class="form-group">
                        <label for="gender">Gender</label>
                        <div>
                            <!-- <input 
                                type="text" class="form-control" name="gender"
                                [(ngModel)]="gender" required /> -->
                            <select class="form-control"
                                [(ngModel)]="gender"
                                [ngModelOptions]="{standalone: true}"
                                >
                                <option value="Male">Male</option>
                                <option value="Female">Female</option>
                            </select>
                        </div>
                    </div>

                    <div class="form-group">
                        <label>Company</label>
                        <div>
                            <input 
                                type="text" class="form-control" 
                                formControlName="ModalCompany" name="company"
                                [(ngModel)]="company" required />
                        </div>
                        <div 
                            class="alert alert-danger"
                            *ngIf="!userForm.controls['ModalCompany'].valid && userForm.controls['ModalCompany'].touched">
                            Error!
                        </div>
                    </div>

                    <div class="form-group">
                        <input 
                            type="submit" 
                            value="Submit"
                            class="btn btn-success">
                    </div>
                </form>
            </div>

            <!-- Modal Footer -->
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
            </div>
        </div>

    </div>
</div>

employee-data.compenent.ts

import { Component } from '@angular/core';
import { Employee } from './employee';
//import { NgForm } from '@angular/forms';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { promise } from 'selenium-webdriver';


@Component({
  selector: 'employee-data',
  templateUrl: './employee-data.component.html',
  styles: [``]
})

export class EmployeeDataComponent {

  userForm: FormGroup;

  constructor(private formBuilder: FormBuilder) {

    this.userForm = this.formBuilder.group({
        'ModalId': ['', Validators.required],
        'ModalName': ['', Validators.required],
        'ModalAddress': ['', Validators.required],
        'ModalCompany': ['', Validators.required]

    })

  }

  id: number;
  name: string;
  address: string;
  gender: string;
  company: string;
  isEditable: boolean;

  //emp: Employee[] = [];

  employees: Employee[] = [
    {
        id: 1,
        name: 'Ram',
        address: 'Kupondole',
        gender: 'Male',
        company: 'XYZ Techno Sales',
        isEditable: false
    },
    {
        id: 2,
        name: 'Shyam',
        address: 'Baneshwor',
        gender: 'Male',
        company: 'ABC Enterprises',
        isEditable: false
    },
    {
        id: 3,
        name: 'Prashansha',
        address: 'Tripureshwor',
        gender: 'Female',
        company: 'MNO Inc',
        isEditable: false
    },
    {
        id: 4,
        name: 'Rita',
        address: 'Ghatthaghar',
        gender: 'Female',
        company: 'Subisu',
        isEditable: false
    }
  ];

  addRow() {
    //prompt("Checking the control!");
    this.employees.push({
        id: this.id,
        name: this.name,
        address: this.address,
        gender: this.gender,
        company: this.company,
        isEditable: this.isEditable

    });
  }

  deleteEmployee(index) {

    this.employees.splice(index, 1);
  }

  editEmployee(index) {

   debugger;
   this.employees[index].isEditable = true;

  }
}

Can anyone help me out cause i’m running out of options!

2

Answers


  1. You are mixing reactive form and template-driven form. I guess what you really want is the reactive form because you are using the FormBuilder.

    Here’s what you need to do.

    Remove template-driven code in your html

    • Remove all the code with [(ngModel)]

    Get the value from the the userForm

    The way you get the value from your form is wrong
    Change your addRow() to this

     addRow() {
         this.id =  this.userForm.controls['ModalId'].value;
         this.name = this.userForm.controls['ModalName'].value;
         //more code here.          
         //you get the picture and do the remaining data.
        this.employees.push({
            id: this.id,
            name: this.name,
            address: this.address,
            gender: this.gender,
            company: this.company,
            isEditable: this.isEditable
    
        });
      }
    

    Hope this helps.

    Login or Signup to reply.
  2. I agree with brijmcq, choose either template driven or reactive form. Do not mix them both. I would build the form as such, that the object you get from the form can be pushed to your array just as it is. By that, just change the form control names so that they match the Employee interface/class.

    So just like brijmcq suggests, remove everything related to template driven form – ngModel and any validators set in template. Use the form group instead:

    this.userForm = this.formBuilder.group({
      id: ['', [Validators.minLength(1), Validators.required]],
      name: ['', Validators.required]
    });
    

    Then just mark the form control names to your form, and on submit, pass the form values:

    <form [formGroup]="userForm" (ngSubmit)="addRow(userForm.value)">  
      <label>Id</label>
      <input type="number" class="form-control" formControlName="id" />
      <div class="alert alert-danger" *ngIf="!userForm.controls['id'].valid && userForm.controls['id'].touched">
        Error!
      </div>
      <!-- more code here -->
    </form>
    

    And then the method for adding the employee, just push the form object to your array and reset form:

    addRow(values) {
      this.employees.push(values);
      this.userForm.reset();
    }
    

    StackBlitz

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search