【发布时间】:2019-02-18 08:51:03
【问题描述】:
我是 Angular 6 的新手,我正在做一个项目,我正在使用带有反应形式的材料设计,它使用表单控制。所以我面临的问题是除了mat-select之外所有其他字段都工作正常,它可以正确显示下拉内容但是当我选择它时,所选值不会反映在表单控件中。 并且 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
有什么帮助和建议吗? 谢谢...
【问题讨论】:
-
您是否有一个
<form>元素,该元素使用正确的formGroup指令包装所有表单控件? The docs site 有一个例子。 -
是的,我有,抱歉忘记粘贴这个问题。
标签: angular6 angular-material2 angular-reactive-forms form-control