如何将用户信息填充到角度编辑表单中

时间:2019-11-10 18:37:09

标签: html angular crud

我有一个应用程序,您可以将学生的名字和姓氏数据导入其中,并将其写入mongodb。我可以创建新的学生,也可以查看数据库中的学生列表,但是在更新时,似乎无法将学生数据填充到名字和姓氏输入字段中。 在我的list-students-component.ts中,我可以选择update,它将更新到(new-student-component)以根据学生ID编辑学生。 我似乎无法弄清楚要填充的数据

<div>
  <ul *ngFor ="let student of students let i = index">
    <li> {{student._id}}: {{student.firstName}} {{student.lastName}} (index {{i}})
      <button mat-button color="warn" (click)="onDelete(student._id)">DELETE</button>
      <button mat-button color="accent" [routerLink]="['/editStudent', student._id]">UPDATE</button>
    </li>
  </ul>
</div>
<div>
  <h3>{{mode}} Student Form</h3>

  <form (ngSubmit)="onSubmit()" #myForm="ngForm">

    <mat-form-field >

      <input matInput placeholder="First Name" id="firstname" [(ngModel)]=" firstName" name="firstname" >
    </mat-form-field>

    <mat-form-field >
      <input matInput placeholder="Last Name" id="lastname" [(ngModel)]=" lastName" name="lastname" >
    </mat-form-field>

    <p>
      <button type="submit" mat-raised-button color="primary">Submit</button>
    </p>

  </form>
</div>
import { Component, OnInit, Input } from '@angular/core';
import { StudentService } from '../student.service';
import { Router } from '@angular/router';
import { ActivatedRoute, ParamMap } from '@angular/router';
import { FormGroup, FormBuilder, FormControl } from '@angular/forms';




@Component({
  selector: 'app-new-student-form',
  templateUrl: './new-student-form.component.html',
  styleUrls: ['./new-student-form.component.css']
})
export class NewStudentFormComponent implements OnInit {


  @Input() firstName: string;
  @Input() lastName: string;
  private mode = 'Add New'; //default mode
  private id: string; //student ID
  public ngForm = new FormGroup({
    firstName: new FormControl('firstName'),
    lastName: new FormControl('lastName')
  })



  constructor(private _myService: StudentService, private router: Router,
    public route: ActivatedRoute) { }
  onSubmit() {
    console.log("You submitted: " + this.firstName + " " + this.lastName);
    this._myService.addStudents(this.firstName, this.lastName);
    this.router.navigate(['/listStudents'])
      .then(() => {
        location.reload();
      });

  }


  ngOnInit() {
    this.route.paramMap.subscribe((paramMap: ParamMap) => {
      if (paramMap.has('_id')) {
        this.mode = 'edit'; /*request had a parameter _id */
        this.id = paramMap.get('_id');

      }



      else {
        this.mode = 'Add New';
        this.id = null;
      }
      if (this.mode == 'Add New')
        this._myService.addStudents(this.firstName, this.lastName);

      if (this.mode == 'edit')
        this.ngForm.value;  
        this._myService.updateStudent(this.id, this.firstName, this.lastName);



    });
  }


}

0 个答案:

没有答案