我在Angular 6下拉数据绑定中遇到问题...
这是非常基本的应用程序,仅供我自学。
很简单。我有单独的Web api端点来获取数据并立即插入数据。
它的简单学生数据。
&这是我的视角。
当用户单击右侧学生网格Edit时,相关数据将加载到左侧表单中。不要考虑这些数据。这些只是临时的。
我对性别有一个下拉列表,因此当用户单击右侧网格时,则必须将性别加载到左侧表单中。 但是那部分不起作用。
左侧组件-StudentRegComponent 右侧组件-StudentListComponent
我试图从StudentListComponent访问StudentRegComponent并绑定下拉数据。那个也不起作用。我认为我的方法有问题 我已经用**突出显示了一些区域,请检查那些地方。
我应该如何处理?
我将添加部分代码。如果您需要完整的代码,请告诉我。
学生服务
import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions, RequestMethod } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
import { Student } from './student.model';
import { Genre } from './genre';
**const genreList = [
new Genre(0, 'Male' ),
new Genre(1, 'Female'),
];**
@Injectable({
providedIn: 'root'
})
export class StudentService {
studentList : Student[];
selectedStudent : Student;
selectedgender : Genre;
constructor(private http : Http) { }
GetGenreList(): Genre[] {
return genreList;
}
PostStudent(student : Student){
console.log('Test');
var body = JSON.stringify(student);
console.log(body);
var headerOptions = new Headers({'Content-Type':'application/json'});
var requestOptions = new RequestOptions({method : RequestMethod.Post,headers : headerOptions});
return this.http.post('http://localhost:57679/Student/Create',body,requestOptions).map(x => x.json());
}
// putEmployee(id, emp) {
// var body = JSON.stringify(emp);
// var headerOptions = new Headers({ 'Content-Type': 'application/json' });
// var requestOptions = new RequestOptions({ method: RequestMethod.Put, headers: headerOptions });
// return this.http.put('http://localhost:28750/api/Employee/' + id,
// body,
// requestOptions).map(res => res.json());
// }
GetStudentList(){
console.log("get data");
this.http.get('http://localhost:57679/Student/GetList')
.map((data : Response) =>{
return data.json() as Student[];
}).toPromise().then(x => {
this.studentList = x;
})
}
UpdateStudent(id, emp) {
var body = JSON.stringify(emp);
var headerOptions = new Headers({ 'Content-Type': 'application/json' });
var requestOptions = new RequestOptions({ method: RequestMethod.Put, headers: headerOptions });
return this.http.put('http://localhost:57679/Student/Update',
body,
requestOptions).map(res => res.json());
}
// deleteEmployee(id: number) {
// return this.http.delete('http://localhost:28750/api/Employee/' + id).map(res => res.json());
// }
}
StudentRegComponent
import { StudentService } from './../shared/student.service';
import { Component, OnInit } from '@angular/core';
import { NgForm } from '@angular/forms';
import { Genre } from '../shared/genre';
@Component({
selector: 'app-student-reg',
templateUrl: './student-reg.component.html',
styleUrls: ['./student-reg.component.css']
})
export class StudentRegComponent implements OnInit {
**genreList: Genre[];
selectedgender = 0;
selectedG : Genre;**
constructor(private studentService : StudentService) { }
ngOnInit() {
this.genreList = this.studentService.GetGenreList();
this.resetForm();
}
onChange(deviceValue) {
console.log("nnnn " + deviceValue);
}
resetForm(form?: NgForm) {
if (form != null)
form.reset();
this.studentService.selectedStudent = {
Id: null,
FirstName: '',
LastName: '',
ParentName: '',
FullName : '',
Gender: this.selectedG,
DOB: ''
}
}
onSubmit(form: NgForm) {
if (form.value.Id == null) {
this.studentService.PostStudent(form.value)
.subscribe(data => {
this.resetForm(form);
this.studentService.GetStudentList();
//this.toastr.success('New Record Added Succcessfully', 'Employee Register');
})
}
else {
this.studentService.UpdateStudent(form.value.Id, form.value)
.subscribe(data => {
this.resetForm(form);
this.studentService.GetStudentList();
// this.toastr.info('Record Updated Successfully!', 'Employee Register');
});
}
}
}
StudentListComponent组件
// import { StudentRegComponent } from './../student-reg/student-reg.component';
import { Student } from './../shared/student.model';
import { StudentService } from './../shared/student.service';
import { Component, OnInit } from '@angular/core';
import { StudentRegComponent } from '../student-reg/student-reg.component';
@Component({
selector: 'app-student-list',
templateUrl: './student-list.component.html',
styleUrls: ['./student-list.component.css']
})
export class StudentListComponent implements OnInit {
constructor(private studentService : StudentService) { }
**saro = new StudentRegComponent(this.studentService);**
ngOnInit() {
this.studentService.GetStudentList();
//this.saro.selectedgender = 1;
// studentRegComponent : StudentRegComponent;
}
showForEdit(std: Student) {
// this.studentService.selectedgender = std.Gender;
this.studentService.selectedStudent = Object.assign({}, std);
// this.saro.selectedgender = 1;
// this.saro.selectedgender = Object.assign({}, 1);
}
key: string = 'name'; //set default
reverse: boolean = false;
sort(key){
console.log('sor');
this.key = key;
this.reverse = !this.reverse;
}
// onDelete(id: number) {
// if (confirm('Are you sure to delete this record ?') == true) {
// this.employeeService.deleteEmployee(id)
// .subscribe(x => {
// this.employeeService.getEmployeeList();
// this.toastr.warning("Deleted Successfully","Employee Register");
// })
// }
// }
}
学生模型
import { Genre } from './genre';
export class Student {
Id :number;
ParentName: string;
FirstName : string;
LastName : string;
FullName : string;
DOB : string;
Gender : Genre;
}
类型模型
export class Genre {
constructor(public id: number, public name: string) {
}
}
StudentListComponent html
<nav class="navbar">
<input class="form-control" type="text" name="search" [(ngModel)]="filter">
</nav>
<table class="table table-sm table-hover">
<!-- <tr *ngFor="let game of games | orderBy: key : reverse | filter:filter | paginate: { itemsPerPage: 5, currentPage: p }; let i = index"> -->
<thead>
<tr>
<th>#</th>
<th (click)="sort('FirstName')">FirstName
<span class="glyphicon sort-icon" *ngIf="key =='FirstName'" [ngClass]="{'glyphicon-chevron-up':reverse,'glyphicon-chevron-down':!reverse}"></span>
</th>
<th (click)="sort('LastName')">LastName
<span class="glyphicon sort-icon" *ngIf="key =='LastName'" [ngClass]="{'glyphicon-chevron-up':reverse,'glyphicon-chevron-down':!reverse}"></span>
</th>
</tr>
</thead>
<tr *ngFor="let student of studentService.studentList | orderBy: key : reverse | filter:filter | paginate: { itemsPerPage: 5, currentPage: p }; let i = index">
<td>{{i}}</td>
<td>{{student.FirstName}}</td>
<td>{{student.LastName}}</td>
<!-- <td>{{student.EmpCode}}</td> -->
<td>
<a class="btn text-warning" (click)="showForEdit(student)">
<i class="">Edit</i>
</a>
<a class="btn text-danger" (click)="onDelete(student.Id)">
<i class="">Delete</i>
</a>
</td>
</tr>
</table>
<pagination-controls (pageChange)="p = $event"></pagination-controls>
StudentRegComponent html
<form class="stdform" #studentForm="ngForm" (ngSubmit)="onSubmit(studentForm)">
<input type="hidden" name="Id" #Id="ngModel" [(ngModel)]="studentService.selectedStudent.Id">
<div class="form-row">
<div class="form-group col-md-6">
<input class="form-control" name="FirstName" #FirstName="ngModel" [(ngModel)]="studentService.selectedStudent.FirstName"
placeholder="First Name" required>
<div class="validation-error" *ngIf="FirstName.invalid && FirstName.touched">This Field is Required.</div>
</div>
<div class="form-group col-md-6">
<input class="form-control" name="LastName" #LastName="ngModel" [(ngModel)]="studentService.selectedStudent.LastName" placeholder="Last Name"
required>
<div class="validation-error" *ngIf="LastName.invalid && LastName.touched">This Field is Required.</div>
</div>
</div>
<div class="form-group">
<input class="form-control" name="ParentName" #ParentName="ngModel" [(ngModel)]="studentService.selectedStudent.ParentName" placeholder="ParentName">
</div>
<div class="form-row">
<div class="form-group col-md-6">
<input class="form-control" name="DOB" #DOB="ngModel" [(ngModel)]="studentService.selectedStudent.DOB" placeholder="Emp DOB">
</div>
<div class="form-group col-md-6">
<select id="gender" name="gender" [(ngModel)]="selectedgender" (ngModelChange)="onChange($event)" class="form-control">
<option *ngFor="let gen of genreList" [value]="gen.id" >
{{gen.name}}
</option>
</select>
<!-- <select id="gender" name="gender" [(ngModel)]="selectedgender" (ngModelChange)="onChange($event)" class="form-control">
<option *ngFor="let gen of genreList" [value]="gen.id" >
{{gen.name}}
</option>
</select> -->
</div>
</div>
<div class="form-row">
<div class="form-group col-md-8">
<button [disabled]="!studentForm.valid" type="submit" class="btn btn-lg btn-block btn-info">
<i class="fa fa-floppy-o"></i> Submit</button>
</div>
<div class="form-group col-md-4">
<button type="button" class="btn btn-lg btn-block btn-secondary" (click)="resetForm(studentForm)">
<i class="fa fa-repeat"></i> Reset</button>
</div>
</div>
</form>
答案 0 :(得分:2)
您要将选择绑定到StudentRegComponent中的 selectedgender -属性([(ngModel)] =“ selectedgender”)。但是此属性永远不会更新。
选择标记中的[(ngModel)] =“ studentService.selectedStudent.Gender.id” 应该可以做您想要的。