Добавление данных в базу данных с помощью этого приложения успешно работает.но когда я пытаюсь отредактировать конкретную запись (документ в mongodb), все остальные поля автоматически заполняются существующими данными в mongodb, но переключатель не выбирается в соответствии со значением, хранящимся в mongodb.
employee.component.html
<div class="row">
<div class="col s12">
<div class="card">
<div class="card-content white-text">
<div class="row">
<div class="col s5">
<form #employeeForm="ngForm" (ngSubmit)="onSubmit(employeeForm)">
<input type="hidden" name="_id" #_id="ngModel" [(ngModel)]="employeeService.selectedEmployee._id">
<div class="row">
<div class="input-field col s12">
<input type="text" name="name" #name="ngModel" [(ngModel)]="employeeService.selectedEmployee.name" placeholder="Enter full name" required>
<label>Name :
<label class="red-text">*</label>
</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<input type="text" name="position" #name="ngModel" [(ngModel)]="employeeService.selectedEmployee.position" placeholder="Eg : Snr. Developer">
<label>Position :</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<input type="text" name="office" #name="ngModel" [(ngModel)]="employeeService.selectedEmployee.office" placeholder="Enter office location">
<label>Office :</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<input type="text" name="salary" #name="ngModel" [(ngModel)]="employeeService.selectedEmployee.salary" placeholder="Salary per annum">
<label>Salary :</label>
</div>
</div>
<p>
<label>
<input name="gender" type="radio" value="1" [(ngModel)]="gender" />
<span>Male</span>
</label>
</p>
<p>
<label>
<input name="gender" type="radio" value="2" [(ngModel)]="gender"/>
<span>Female</span>
</label>
</p>
<div class="row">
<div class="input-field col s12">
<button class="btn btn-custom right" type="button" (click)="resetForm(employeeForm)">Reset</button>
<button class="btn btn-custom right" type="submit" [disabled]="!employeeForm.valid">Submit</button>
</div>
</div>
</form>
</div>
<div class="col s7">
<table class="responsive-table highlight">
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th></th>
</tr>
</thead>
<tr *ngFor="let emp of employeeService.employees">
<td>{{emp.name}}</td>
<td>{{emp.position}}</td>
<td>{{emp.office}}</td>
<td>
<a class="action-btn" (click)="onEdit(emp)">
<i class="material-icons">edit</i>
</a>
<a class="action-btn" (click)="onDelete(emp._id,employeeForm)">
<i class="material-icons">delete</i>
</a>
</td>
</tr>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
employee.component.ts
import { Component, OnInit } from '@angular/core';
import { NgForm } from '@angular/forms';
import { EmployeeService } from '../shared/employee.service';
import { Employee } from '../shared/employee.model';
declare var M: any;
@Component({
selector: 'app-employee',
templateUrl: './employee.component.html',
styleUrls: ['./employee.component.css'],
providers: [EmployeeService]
})
export class EmployeeComponent implements OnInit {
constructor(private employeeService: EmployeeService) { }
ngOnInit() {
this.resetForm();
this.refreshEmployeeList();
}
resetForm(form?: NgForm) {
if (form)
form.reset();
this.employeeService.selectedEmployee = {
_id: "",
name: "",
position: "",
office: "",
salary: null,
gender: null
}
}
onSubmit(form: NgForm) {
if (form.value._id == "") {
this.employeeService.postEmployee(form.value).subscribe((res) => {
this.resetForm(form);
this.refreshEmployeeList();
M.toast({ html: 'Saved successfully', classes: 'rounded' });
});
}
else {
this.employeeService.putEmployee(form.value).subscribe((res) => {
this.resetForm(form);
this.refreshEmployeeList();
M.toast({ html: 'Updated successfully', classes: 'rounded' });
});
}
}
refreshEmployeeList() {
this.employeeService.getEmployeeList().subscribe((res) => {
this.employeeService.employees = res as Employee[];
});
}
onEdit(emp: Employee) {
this.employeeService.selectedEmployee = emp;
}
onDelete(_id: string, form: NgForm) {
if (confirm('Are you sure to delete this record ?') == true) {
this.employeeService.deleteEmployee(_id).subscribe((res) => {
this.refreshEmployeeList();
this.resetForm(form);
M.toast({ html: 'Deleted successfully', classes: 'rounded' });
});
}
}
}
employeeController.js
const express = require('express');
var router = express.Router();
var ObjectId = require('mongoose').Types.ObjectId;
var { Employee } = require('../models/employee');
// => localhost:3000/employees/
router.get('/', (req, res) => {
Employee.find((err, docs) => {
if (!err) { res.send(docs); }
else { console.log('Error in Retriving Employees :' + JSON.stringify(err, undefined, 2)); }
});
});
router.get('/:id', (req, res) => {
if (!ObjectId.isValid(req.params.id))
return res.status(400).send(`No record with given id : ${req.params.id}`);
Employee.findById(req.params.id, (err, doc) => {
if (!err) { res.send(doc); }
else { console.log('Error in Retriving Employee :' + JSON.stringify(err, undefined, 2)); }
});
});
router.post('/', (req, res) => {
var emp = new Employee({
name: req.body.name,
position: req.body.position,
office: req.body.office,
salary: req.body.salary,
gender: req.body.gender,
});
emp.save((err, doc) => {
if (!err) { res.send(doc); }
else { console.log('Error in Employee Save :' + JSON.stringify(err, undefined, 2)); }
});
});
router.put('/:id', (req, res) => {
if (!ObjectId.isValid(req.params.id))
return res.status(400).send(`No record with given id : ${req.params.id}`);
var emp = {
name: req.body.name,
position: req.body.position,
office: req.body.office,
salary: req.body.salary,
gender: req.body.gender,
};
Employee.findByIdAndUpdate(req.params.id, { $set: emp }, { new: true }, (err, doc) => {
if (!err) { res.send(doc); }
else { console.log('Error in Employee Update :' + JSON.stringify(err, undefined, 2)); }
});
});
router.delete('/:id', (req, res) => {
if (!ObjectId.isValid(req.params.id))
return res.status(400).send(`No record with given id : ${req.params.id}`);
Employee.findByIdAndRemove(req.params.id, (err, doc) => {
if (!err) { res.send(doc); }
else { console.log('Error in Employee Delete :' + JSON.stringify(err, undefined, 2)); }
});
});
module.exports = router;
Это изображение (https://imgur.com/82VbxBJ) текущего состояния формы редактирования. Мне нужно, чтобы этот переключатель был выбран в соответствии со значением, хранящимся в mongodb.