How to connect the form in angular routing

2019-08-27 17:53发布

问题:

i have added angular routing to my crud operation.. before without routing the data i added was able to display in the table but now after implementation of routing the data is not getting stored in the table

here is the code of createemployee.component.html

<h2>Add Employee:</h2>
      <form class="form-horizontal" #empForm="ngForm">
        <div class="form-group">
          <label class="control-label col-sm-2" for="name">Name:</label>
          <div class="col-sm-10">
            <input type="text"  class="form-control" name="name"  minlength="4" maxlength="10"  pattern="^[A-Za-z0-9]*[A-Za-z0-9][A-Za-z0-9]\S*$" [(ngModel)]="model.name" placeholder="Enter Your Name"
                   #name="ngModel" required/>
            <div *ngIf="name.invalid && (name.dirty || name.touched)" class="alert alert-danger">
              <div *ngIf="name.errors.required">
                Name is required.
              </div>
              <div *ngIf="name.errors.pattern">
                No Spaces
              </div>
              <div *ngIf="name.errors.minlength">
                Name must be at least 4 characters long.
              </div>
            </div>
          </div>
        </div>
       <div class="form-group">
          <label class="control-label col-sm-2" for="position">Position:</label>

          <div class="col-sm-10">
            <input type="text" class="form-control" name="position" minlength="4" maxlength="10" pattern="^[a-z]*$" [(ngModel)]="model.position" placeholder="Enter your position"
                   #position="ngModel" required />
            <div *ngIf="position.invalid && (position.dirty || position.touched)" class="alert alert-danger">
              <div *ngIf="position.errors.required">
                Position is required.
              </div>
              <div *ngIf="position.errors.pattern">
                Only Alphabets are must be entered
              </div>
              <div *ngIf="position.errors.minlength">
                Position must be at least 4 characters long.
              </div>
            </div>
          </div>
        </div>
        <div class="form-group">
          <label class="control-label col-sm-2" for="salary">Salary:</label>
          <div class="col-sm-10">
            <input type="text" class="form-control" name="salary" pattern="[0-9]*"
                   minlength="5" maxlength="7"  [(ngModel)]="model.salary" placeholder="Enter Salary" #salary="ngModel" required />
            <div *ngIf="salary.invalid && (salary.dirty || salary.touched)" class="alert alert-danger">
              <div *ngIf="salary.errors.required">
                Salary is required.
              </div>
              <div *ngIf="salary.errors.minlength">
                Salary must be in 5 numbers.
              </div>
              <div *ngIf="salary.errors.maxlength">
                Salary must not be exceeded morethan 7 numbers.
              </div>

              <div *ngIf="salary.errors?.pattern">Only numebers should be typed
              </div>
            </div>
          </div>
        </div>
        <div class="form-group">
          <div class="col-sm-offset-2 col-sm-10">
            <button type="submit" class="btn btn-default" routerLink="../viewemployee" [disabled]="empForm.invalid">Add Employee</button>
            <button type="button" class="btn btn-default" routerLink="../home">Cancel</button>
          </div>
        </div>
      </form>

createemployee.component.ts

import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup , Validators} from '@angular/forms';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';

@Component({
  selector: 'app-createemployee',
  templateUrl: './createemployee.component.html',
  styleUrls: ['./createemployee.component.css']
})

export class CreateemployeeComponent implements OnInit {

  model: any = {};
  model2: any = {};
  add=false;
  create=true;

  ngOnInit() {
    this.model = new FormGroup({
      'name': new FormControl(this.model.name,
        [Validators.required, Validators.minLength(4),]),
      'position': new FormControl(this.model.position,
        [Validators.required, Validators.minLength(4),]),
      'salary': new FormControl(this.model.salary, Validators.required)
    });
  }

  employees = [{name: "Sunil", position: "Developer", salary: 20000},
    {name: "Vamshi", position: "Java Developer", salary: 30000},
    {name: "Chethan", position: ".Net Developer", salary: 10000}];

  createEmp(){
    this.add=true;
    this.create=false;
    this.Show=false;
    this.edit=false;
  }
  addEmployee() {
    this.employees.push(this.model);
    this.Show = true;
    this.add = false;
    this.model = {};
  }
}

viewemployeecomponent.ts

<h2>Employee Details</h2>
  <table class="table table-bordered">
    <thead>
    <tr>
      <th width=400>Name</th>
      <th width=400>Position</th>
      <th width=200>Salary</th>
      <th width=400>Actions</th>
    </tr>
    </thead>
    <tbody>
    <tr *ngFor="let employee of employees; let i=index">
      <td>{{employee.name}}</td>
      <td>{{employee.position}}</td>
      <td>{{employee.salary}}</td>
      <td>
        <a class="btn btn-success" (click)="editEmployee(i)">Edit</a>
        <a class="btn btn-danger" (click)="deleteEmployee(i)">Delete</a>
      </td>
    </tr>
    </tbody>
  </table>

app.router.ts

import { ModuleWithProviders } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { CreateemployeeComponent } from './createemployee/createemployee.component';
import { ViewemployeeComponent } from './viewemployee/viewemployee.component';
import { UpdateemployeeComponent } from './updateemployee/updateemployee.component';

export const router: Routes = [
  { path: '',redirectTo: 'home',pathMatch: 'full'},
  { path: 'createemployee', component: CreateemployeeComponent },
  { path: 'updateemployee', component: UpdateemployeeComponent},
  { path: 'viewemployee', component: ViewemployeeComponent },
  { path: 'home', component: HomeComponent},
  { path: 'appcomponent', component: AppComponent}
];

export const routes: ModuleWithProviders = RouterModule.forRoot(router)

where did i have done the mistake.. i am trying to add the created employee into existing table with all other 3 hard coded employees

回答1:

form what i ca see your problem is you're pushing a new employee in a component ..but you render the employee table in another and i see yours employee array is not from a service or from a @input() directive ...

so for example create a service like:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Rx';
import { environment } from '../../../../environments/environment';
import { PraticheGridVM, PraticheDTO } from 'app/awards/shared/models';


@Injectable()
export class EmployeeService {

private  employees = [{name: "Sunil", position: "Developer", salary: 20000},
    {name: "Vamshi", position: "Java Developer", salary: 30000},
    {name: "Chethan", position: ".Net Developer", salary: 10000}];


  constructor(private http: HttpClient) { }


  /**
   * Get Pratiche Mese Paginate
   * @param {PraticheGridVM} filter 
   * @returns {Promise<Array<PraticheDTO>>} 
   * @memberof PraticheService
   */
  public   GetEmployee(): Array<Employee> {
    return this.employees;
  }



  /**
   * Get Pratiche Trimestre Paginate
   * @param {PraticheGridVM} filter 
   * @returns {Promise<PraticheDTO>} 
   * @memberof PraticheService
   */
  public   AddEmployee(emp: Employee): Array<Employee> {
    return this.employees.push(emp);
  }



}

and then use it in your components .. like:

import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup , Validators} from '@angular/forms';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import {EmployeeService} from 'yourservicePATH'

@Component({
  selector: 'app-createemployee',
  templateUrl: './createemployee.component.html',
  styleUrls: ['./createemployee.component.css']
})

export class CreateemployeeComponent implements OnInit {

  model: any = {};
  model2: any = {};
  add=false;
  create=true;

constructor(private employeeService: EmployeeService){

}

  ngOnInit() {
    this.model = new FormGroup({
      'name': new FormControl(this.model.name,
        [Validators.required, Validators.minLength(4),]),
      'position': new FormControl(this.model.position,
        [Validators.required, Validators.minLength(4),]),
      'salary': new FormControl(this.model.salary, Validators.required)
    });
  }

  employees = [{name: "Sunil", position: "Developer", salary: 20000},
    {name: "Vamshi", position: "Java Developer", salary: 30000},
    {name: "Chethan", position: ".Net Developer", salary: 10000}];

  createEmp(){
    this.add=true;
    this.create=false;
    this.Show=false;
    this.edit=false;
  }
  addEmployee() {
    this.employeeService.AddEmployee(this.model);
    this.Show = true;
    this.add = false;
    this.model = {};
  }
}