好的,所以我有以下组件:
import { Component, Input, Output, EventEmitter } from '@angular/core';
import { Nightshelter } from "app/nightshelter/models/nightshelter.interface";
import { FormGroup } from "@angular/forms";
@Component({
selector: 'nightshelter-dropdown',
template: `
<div [formGroup]="parent">
<pre>{{parent.value|json}}</pre>
<select #nightshelterDropdown (change)="yearChanged(nightshelterDropdown)" formControlName="nightshelterId" class="form-control input-sm">
<option value="">Select</option>
<option *ngFor="let nightshelter of nightshelters"
[value]="nightshelter.id"
[selected]="nightshelter.id == nightshelterId">
{{nightshelter.title}}
</option>
</select>
</div>
`
})
export class NightshelterDropdownComponent {
@Input()
nightshelters: Nightshelter[];
@Output()
handleNightshelterYearChange: EventEmitter<string> = new EventEmitter<string>();
@Input()
parent: FormGroup;
yearChanged(nightshelterDropdown): void {
console.log('changing value to')
this.handleNightshelterYearChange.emit(nightshelterDropdown.value)
}
}
该json管道的相关结果是:
{
"id": null,
"nightshelterId": "2",
我的组件被渲染为:
<nightshelter-dropdown>
<div class="ng-pristine ng-valid ng-touched">
<select class="form-control input-sm ng-pristine ng-valid ng-touched" formcontrolname="nightshelterId">
<option value="">Select</option>
<!----><option value="2">
Nightshelter 2015-2016
</option>
</select>
</div>
</nightshelter-dropdown>
我遇到的问题是尽管nighthelterId在反应形式中有价值,因此json是正确的,我的下拉值没有被选中。
这在本地完美运行(即使在切换到生产模式时)
然而,在服务器上,它只是选择了“选择”。
有什么想法吗?
答案 0 :(得分:0)
试试这个:
<select #nightshelterDropdown
[(ngModel)]="nightshelter.id"
(ngModelChange)="yearChanged($event)"
formControlName="nightshelterId"
class="form-control input-sm">
<option value="0">Select</option>
<option *ngFor="let nightshelter of nightshelters"
value={{nightshelter.id}}>
{{nightshelter.title}}
</option>
</select>
yearChanged(value): void {
this.nightshelter.id = value;
console.log(`changing value to ${this.nightshelter.id}`);
}