我是Angular 6的新手,我正在一个项目中,我在材料设计中使用带有表单控制的反应形式。因此,我面临的问题是,除了mat-select之外,其他所有字段都工作正常,它可以正确显示下拉内容,但是当我选择它时,所选值不会反映在表单控件中。 垫选择数据来自后端
这是我的html代码:
<mat-form-field class="example-full-width">
<mat-select placeholder="Source City" formControlName="sourceCityControl" required [errorStateMatcher]="matcher">
<mat-option *ngFor="let city of cities" [value]="city">
{{city.name}}
</mat-option>
</mat-select>
<mat-error>
Source City <strong> Required </strong>
</mat-error>
</mat-form-field>
<br> <br>
<mat-form-field class="example-full-width">
<mat-select placeholder="Destination City" formControlName="destinationCityControl" required [errorStateMatcher]="matcher">
<mat-option *ngFor="let city of cities" [value]="city">
{{city.name}}
</mat-option>
</mat-select>
<mat-error>
Destination City <strong> Required </strong>
</mat-error>
</mat-form-field>
<!-- other form elements -->
<!-- to check form elements -->
{{profileForm.value | json}}
这是我的TypeScript文件代码:
public cities = [];
minDate = new Date();
nextdate = this.minDate.getUTCDate();
nextmonth = this.minDate.getUTCMonth();
nextyear = this.minDate.getFullYear();
maxDate = new Date(this.nextyear, this.nextmonth + 1, this.nextdate);
host: Oldoffer;
offerModel: any;
matcher = new MyErrorStateMatcher();
constructor(private fb: FormBuilder, private _offerService:
OfferRideService, private router: Router, private editService: EditService)
{ }
test1: string;
test2: Date;
test3: Date;
profileForm: FormGroup;
ngOnInit() {
console.log(this.nextdate);
this._offerService.getCities().subscribe(data => this.cities = data);
this.editService.getHost().subscribe((data) => {
this.host = data;
this.test1 = this.host.date.toString();
this.test2 = new Date(this.test1.slice(0, 19) + 'Z');
this.test3 = new Date(this.test2.getFullYear(), this.test2.getUTCMonth(),
this.test2.getUTCDate())
this.profileForm = new FormGroup({
sourceCityControl: new FormControl('', Validators.required),
destinationCityControl: new FormControl('', Validators.required),
dateControl: new FormControl(this.test3, Validators.required),
seatsControl: new FormControl(this.host.noOfSeats, [Validators.required,
Validators.min(1), Validators.max(4)]),
amountControl: new FormControl(this.host.amount, [Validators.required,
Validators.min(0), Validators.max(2000)]),
acControl: new FormControl(this.host.preference.ac),
musicControl: new FormControl(this.host.preference.music),
smokingControl: new FormControl(this.host.preference.smoking),
petsControl: new FormControl(this.host.preference.pets)
});
})
}//other code omitted
有什么帮助和建议吗? 谢谢...
答案 0 :(得分:0)
我将您的问题复制到最简单的形式,这就是您所缺少的:您可能会从其他formContorls中丢失<form>
元素,因此请确保始终关注控制台。如果您不熟悉Angular,它将成为您最好的朋友。另外,在构建FormGroups时,请查看它的文档,因为这不是一个好方法。
只要遵循我为您构建的示例,它就可以解决您的问题:https://stackblitz.com/edit/angular-nbihkv