如何在角度路由中连接表单 [英] How to connect the form in angular routing

查看:107
本文介绍了如何在角度路由中连接表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我添加了角路由到我的crud操作..在没有路由之前,我添加的数据能够显示在表中,但是现在在执行路由之后,数据不会被存储在表中。



这里是createemployee.component.html的代码。

 < h2>添加员工:< ; / H2> 
< form class =form-horizo​​ntal#empForm =ngForm>
< div class =form-group>
< label class =control-label col-sm-2for =name>名称:< / label>
< div class =col-sm-10>
< input type =textclass =form-controlname =nameminlength =4maxlength =10pattern =^ [A-Za-z0-9] * [A -Za-z0-9] [A-Za-z0-9] \S * $[(ngModel)] =model.nameplaceholder =输入您的姓名
#name =ngModel需要/>
< div * ngIf =name.invalid&&(name.dirty || name.touched)class =alert alert-danger>
< div * ngIf =name.errors.required>
名称是必需的。
< / div>
< div * ngIf =name.errors.pattern>
无空格
< / div>
< div * ngIf =name.errors.minlength>
名称必须至少有4个字符。
< / div>
< / div>
< / div>
< / div>
< div class =form-group>
< label class =control-label col-sm-2for =position>位置:< / label>

< div class =col-sm-10>
#position =ngModelrequired />
< div * ngIf =position.invalid&&(position.dirty || position.touched)class =alert alert-danger>
< div * ngIf =position.errors.required>
位置是必需的。
< / div>
< div * ngIf =position.errors.pattern>
只有字母必须输入
< / div>
< div * ngIf =position.errors.minlength>
位置必须至少有4个字符。
< / div>
< / div>
< / div>
< / div>
< div class =form-group>
< label class =control-label col-sm-2for =salary>薪酬:< / label>
< div class =col-sm-10>
minlength =5maxlength =7[( ngModel)] =model.salaryplaceholder =Enter Salary#salary =ngModelrequired />
< div * ngIf =salary.invalid&&(salary.dirty || salary.touched)class =alert alert-danger>
< div * ngIf =salary.errors.required>
薪水是必需的。
< / div>
< div * ngIf =salary.errors.minlength>
薪水必须是5个数字。
< / div>
< div * ngIf =salary.errors.maxlength>
工资不能超过7个数字。
< / div>

< div * ngIf =salary.errors?.pattern>只有数字符号应该输入
< / div>
< / div>
< / div>
< / div>
< div class =form-group>
< div class =col-sm-offset-2 col-sm-10>
< button type =submitclass =btn btn-defaultrouterLink =../ viewemployee[disabled] =empForm.invalid>添加员工< / button>
< button type =buttonclass =btn btn-defaultrouterLink =../ home>取消< / button>
< / div>
< / div>
< / form>

createemployee.component.ts

 从'@ angular / core'导入{Component,OnInit}; 
从'@ angular / forms'导入{FormControl,FormGroup,Validators};
从'@ angular / forms'导入{FormsModule,ReactiveFormsModule};

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

导出类CreateemployeeComponent实现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)
});
}

雇员= [{名称:Sunil,职位:开发人员,工资:20000},
{姓名:Vamshi,职位: ,薪水:30000},
{姓名:Chethan,职位:.Net Developer,工资: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>员工详情< / h2> 
< table class =table table-bordered>
< thead>
< tr>
< th width = 400>名称< / th>
< th width = 400>位置< / th>
< th width = 200>薪酬< / th>
< th width = 400>动作< / th>
< / tr>
< / thead>
< tbody>
< tr * ngFor =让雇员雇员;让我=索引>
< td> {{employee.name}}< / td>
< td> {{employee.position}}< / td>
< td> {{employee.salary}}< / td>
< td>
< a class =btn btn-success(click)=editEmployee(i)>编辑< / a>
< / td>
< / tr>
< / tbody>
< / table>

app.router.ts

 从'@ angular / core'导入{ModuleWithProviders}; 
从'@ angular / router'导入{Routes,RouterModule};

从'./app.component'导入{AppComponent};
从'./home/home.component'导入{HomeComponent};
从'./createemployee/createemployee.component'中导入{CreateemployeeComponent};
从'./viewemployee/viewemployee.component'中导入{ViewemployeeComponent};
从'./updateemployee/updateemployee.component'导入{UpdateemployeeComponent};

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)

其中我是否犯了这个错误..我正试图将已创建的员工与所有其他3位硬编码员工一起添加到现有表中。

>形成我可以看到你的问题是你推动一个新的员工在一个组件..但你在另一个渲染员工表,我看到你的员工数组不是从服务或@input()指令.. 。

例如创建一个服务,如:

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


@Injectable()
export class EmployeeService {

private employees = [{name:Sunil,position:Developer,salary :20000},
{姓名:Vamshi,职位:Java开发人员,工资:30000},
{姓名:Chethan,职位:.Net Developer ]。


构造函数(private http:HttpClient){}

$ b / **
*获取Pratiche Mese分页
* @param {PraticheGridVM}过滤器
* @returns {Promise< Array< PraticheDTO>>}
* @memberof PraticheService
* /
public GetEmployee():Array< Employee> {
返回this.employees;
}



/ **
*获取Pratiche Trimestre分页
* @param {PraticheGridVM}过滤
* @返回{Pr​​omise< PraticheDTO>}
* @memberof PraticheService
* /
public AddEmployee(emp:Employee):Array< Employee> {
返回this.employees.push(emp);
}



}

然后在你的组件中使用它。例如:

 从'@ angular / core'导入{Component,OnInit}; 
从'@ angular / forms'导入{FormControl,FormGroup,Validators};
从'@ angular / forms'导入{FormsModule,ReactiveFormsModule};
从'yourservicePATH'导入{EmployeeService}

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

导出类CreateemployeeComponent实现OnInit {

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

构造函数(private employeeService:EmployeeService){

}

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

雇员= [{名称:Sunil,职位:开发人员,工资:20000},
{姓名:Vamshi,职位: ,薪水:30000},
{姓名:Chethan,职位:.Net Developer,工资: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 = {};
}
}


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

解决方案

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 = {};
  }
}

这篇关于如何在角度路由中连接表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆