【问题标题】:How to connect the form in angular routing如何在角度路由中连接表单
【发布时间】:2017-09-25 20:20:38
【问题描述】:

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

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

查看employeecomponent.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)

我在哪里做错了.. 我正在尝试将创建的员工与所有其他 3 名硬编码员工一起添加到现有表中

【问题讨论】:

    标签: html angular angular-routing


    【解决方案1】:

    我可以看到你的问题是你在一个组件中推送一个新员工..但是你在另一个中呈现员工表,我看到你的员工数组不是来自服务或来自 @input() 指令...

    所以例如创建一个服务,如:

    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);
      }
    
    
    
    }
    

    然后在你的组件中使用它......比如:

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

    【讨论】:

    • Array 是做什么用的?
    • 未捕获(承诺):错误:没有 EmployeeService 的提供者!...我在 employeeservice.ts 文件中添加了提供者
    • 在你写完你的服务文件后不...将它包含在providers下的app.module.ts文件中
    猜你喜欢
    • 2022-12-03
    • 2017-12-02
    • 2018-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-13
    相关资源
    最近更新 更多