我有一个jQuery DataTables,用于列出学生的“添加新”按钮。单击“添加新”时,将从另一个component.ts
文件打开模式。
保存记录后,它会显示在DataTable列表中,但没有DataTable操作像新输入的记录或分页更新或过滤那样搜索。
总体而言我们需要刷新表,以便更新DataTable中的数据。我不熟悉modal.component.ts
文件中student.compnent.ts
刷新表的方式。
Student.component.ts
import {Component, OnInit} from '@angular/core';
import {StudentService} from "../../services/student.service";
import {CompanyService} from "../../services/company.service";
import {Student} from "../../models/student";
import { Router } from '@angular/router';
declare var $: any;
declare var jQuery: any;
@Component({
selector: 'my-students',
templateUrl: './students.component.html'
})
export class StudentsComponent implements OnInit {
students: Student[];
selectedStudent: Student;
sources: any;
error: any;
constructor(private router: Router, private studentService: StudentService, private companyService: CompanyService) {
}
getStudents() {
this.studentService.getStudents().then(students => {
this.students = students
$(function () {
var oTable = $('#example2').DataTable({
"bPaginate" : $('#example2 tbody tr').length>3,
"iDisplayLength": 3,
"bAutoWidth": false,
"bInfo" : true
});
$('#advance_search').keyup(function(){
oTable.search($(this).val()).draw() ;
});
});
});
}
ngOnInit() {
this.companyService.getCompany().then(companyData => {
if(companyData) {
this.sources = companyData.sources;
}
});
this.getStudents();
}
studentChanged(event) {
var changedItem = event;
var findChangedItem = this.students.find( item => {
return item._id == changedItem._id;
});
if(findChangedItem) {
console.log('TODO: update students data in list.');
} else {
this.students.push(changedItem);
}
}
sourcesUpdated(event) {
this.sources = event;
}
detailsStudent(_id) {
this.router.navigate(['/app/studentdetails', _id]);
}
}
addstudent.component.ts(模态组件)
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import {Component, Input,Output, EventEmitter, OnInit,ViewChild, ElementRef} from '@angular/core';
import { NotificationsService } from 'angular2-notifications';
import { IMyDateModel, IMyDpOptions } from 'mydatepicker';
import { ActivatedRoute, Params } from '@angular/router';
import {Address} from "../models/address";
import {Student} from "../models/student";
import {Company} from "../models/company";
import {StudentService} from "../services/student.service";
import {CompanyService} from "../services/company.service";
import { ValidationService } from '../services/validation.service';
declare var moment: any;
@Component({
selector: 'popup-addstudent',
templateUrl: './addstudent.component.html'
})
export class AddStudentsComponent implements OnInit {
student: Student;
// sources: Sources[];
error: any;
navigated = false; // true if navigated here
studentForm: any;
sources: any;
studentAddress: Address;
//companyData: Company;
@ViewChild('studentCloseBtn') studentCloseBtn: ElementRef;
@Input()
set sourceList(sourceList: any) {
this.sources = sourceList;
}
@Output()
loadChanges: EventEmitter
<any>
= new EventEmitter
<any>
();
visaExpiresOn: any;
visaExpiresOnFormatted: any = null;
public myDatePickerOptions: IMyDpOptions = {
dateFormat: 'dd/mm/yyyy',
};
constructor(private studentService: StudentService, private companyService: CompanyService, private formBuilder: FormBuilder,
private route: ActivatedRoute, private validationService: ValidationService, private notificationsService: NotificationsService) {
this.student = new Student();
this.validationService= validationService;
this.reload();
}
ngOnInit() {
}
//convert from :date:{year: 2017, month: 9, day: 13}
onDateChanged(event: IMyDateModel) {
//set the date to yymmdd format for saving
this.visaExpiresOnFormatted = moment(event.formatted, "DD/MM/YYYY").format('YYYY-MM-DD');
console.log("date changed");
console.log(this.visaExpiresOnFormatted);
}
save() {
if (this.studentForm.valid) {
this.student.visaExpiresOn = this.visaExpiresOnFormatted;
console.log("in save");
console.log(this.student);
this.studentService
.save(this.student)
.then(student => {
this.loadChanges.emit(student);
this.student = student; // saved student, w/ id if new
this.notificationsService.success(
'Saved',
'Student saved successfully.',
{
timeOut: 5000,
showProgressBar: true,
pauseOnHover: false,
clickToClose: false,
maxLength: 110
}
);
this.student = new Student();
this.closeModal();
})
.catch(error => {
this.error = error;
console.log(error);
// Show alert error message.
this.notificationsService.error(
'Not Saved',
'Some error occured.',
{
timeOut: 5000,
showProgressBar: true,
pauseOnHover: false,
clickToClose: false,
maxLength: 50
}
);
});
}
else{
// Show alert message.
this.error = "Please enter required fields!";
this.validationService.validateAllFormFields(this.studentForm);
}
}
reload() {
this.error = null;
this.studentForm = this.formBuilder.group({
'firstName': ['', Validators.required],
'lastName': ['', Validators.required],
'middleName': [''],
'address1': [''],
'address2': [''],
'city': ['', []],
'state': ['', []],
'country': ['', []],
'postcode': ['', []],
'phone': [''],
'source':[''],
'visaExpiresOn': [''],
'isVisa': [''],
'email': ['', [Validators.required]]
});
this.student = new Student();
this.studentAddress = this.student.address;
}
closeModal(): void {
this.studentCloseBtn.nativeElement.click();
}
//allowd only number
keyPress(event: any) {
const pattern = /^[0-9._-]+$/ ;
let inputChar = String.fromCharCode(event.charCode);
//console.log("dot...."+event.keyCode);
if(([8, 9, 13, 27, 37, 38, 39, 40, 46,110,190].indexOf(event.keyCode) == -1 ) && !pattern.test(inputChar)) {
if (!pattern.test(inputChar)) {
event.preventDefault();
}
}
}
}
addstudent.component.html
<div class="modal-dialog">
<!-- Modal content-->
<form [formGroup]="studentForm" (submit)="save()">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close" #studentCloseBtn >
<span aria-hidden="true">×</span>
</button>
<h3 class="modal-title">Add Student</h3>
</div>
<div *ngIf="student" class="box box-body modal-body" style="padding:25px 10px">
<div *ngIf="error" class="alert alert-danger text-center">{{ error }}</div>
<div class="col-md-10 col-md-offset-1 col-md-offset-right-1" style="margin-top:20px;">
<div class="row">
<div class="form-group col-md-4">
<input formControlName="firstName" id="firstName" title="First Name" placeholder="FIRST NAME *" type="text" class="form-control adstu_btn" [(ngModel)]="student.firstName" />
<control-messages [control]="studentForm.controls.firstName"></control-messages>
</div>
<div class="form-group col-md-4">
<input formControlName="middleName" type="text" title="Middle Name" [(ngModel)]="student.middleName" class="form-control adstu_btn" placeholder="MIDDLE NAME" autocomplete="off" />
</div>
<div class="form-group col-md-4">
<input formControlName="lastName" type="text" title="Last Name" [(ngModel)]="student.lastName" class="form-control adstu_btn" placeholder="LAST NAME *" autocomplete="off" required />
<control-messages [control]="studentForm.controls.lastName"></control-messages>
</div>
</div>
<div class="row">
<div class="form-group col-md-12">
<input formControlName="phone" type="text" title="Telephone" [(ngModel)]="student.phone" class="form-control adstu_btn" placeholder="TEL" autocomplete="off" (keypress)="keyPress($event)" />
</div>
</div>
<div class="row">
<div class="form-group col-md-12">
<input formControlName="email" type="text" title="Email" [(ngModel)]="student.email" class="form-control adstu_btn" placeholder="EMAIL *" autocomplete="off" required />
<control-messages [control]="studentForm.controls.email"></control-messages>
</div>
</div>
<div class="row">
<div class="form-group col-md-10 col-xs-10">
<select formControlName="source" title="Source" class="form-control round" [(ngModel)]="student.source" >
<option *ngFor="let sourceval of sources" [ngValue] = "sourceval._id" >{{sourceval.sourceName}}</option>
</select>
</div>
<div class="col-md-2 col-xs-2 button-bottom" style="margin-top:7px !important" >
<a href="#" class="plusbtn1" title="Add Source" data-toggle="modal" data-target="#addSource"><span>+</span></a>
</div>
</div>
<div class="row">
<div class="col-md-7 col-sm-12" >
<div class="form-group">
<my-date-picker formControlName="visaExpiresOn" title="Student Visa Expiry Date" name="visaExpiresOn" [(ngModel)]="visaExpiresOn" [options]="myDatePickerOptions" placeholder="VISA EXPIRES ON"
(dateChanged)="onDateChanged($event)" >
</my-date-picker>
<control-messages [control]="studentForm.controls.visaExpiresOn"></control-messages>
</div>
</div>
<div class="col-md-5 col-sm-12" >
<div style="margin-top: 12px;" class="form-group">
<input formControlName="isVisa" type="checkbox" [(ngModel)]="student.isVisa" >
<label class="" id="Label_padding">No Student Visa</label>
<control-messages [control]="studentForm.controls.isVisa"></control-messages>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary" >Add</button>
<button type="button" class="btn btn-default btn-default1" data-dismiss="modal">Cancel</button>
</div>
</div>
</form>
</div>