【发布时间】:2017-05-22 04:33:17
【问题描述】:
我遇到了与Drop Down List in Angular 2 Model Driven Form 中描述的类似的问题(尽管模型绑定到选择框要简单得多)。
模板很简单,基本上是一个'Dear x'的列表,其中x是由服务提供的:
<form novalidate [formGroup]="myForm">
<div class="form-group">
<label for="salutation">Dear ...</label>
<select id="salutation"
class="form-control"
formControlName="salutation">
<option value="">Please select how to address the customer</option>
<option *ngFor="let sal of salutations"
[value]="sal">{{sal}}
</option>
</select>
</div>
</form>
在组件中,我订阅了一项服务,该服务获取此选择框的数据(console.log 表明数据确实到达了)。
ngOnInit() {
this.createFormControls();
this.createForm();
this.proposalStateService.emitProposal.subscribe(
data => {
console.log('subscribe fired: ');
console.log(data);
this.salutations = [
'Mr & Mrs ' + data.last_name,
'Mrs ' + data.last_name,
'Ms ' + data.last_name,
'Mr ' + data.last_name,
data.first_name
];
}
);
}
createFormControls() {
this.salutation = new FormControl(this.salutations, Validators.required);
}
createForm() {
this.myForm = new FormGroup({
salutation: this.salutation
});
}
我已经尝试了这些方法来让表单使用服务中的值进行更新,但它们似乎都不起作用:
-
重置组
this.myForm = this.formBuilder.group({ salutation: [this.salutations] }); -
修补表单上的值
this.myForm.patchValue(this.salutation, this.salutations); -
在控件上设置值
this.salutation.setValue(this.salutations); -
通过表单设置值
this.myForm.controls['salutation'].setValue(this.salutations);
显然我遗漏了一些东西......但是什么?
编辑原始问题
有时控制台会显示数据到达,但在清理我的代码并经过进一步测试后,console.log 事件现在不会在此组件加载时显示。我认为这一定是时间问题 - 可能组件在发出所需数据的服务已经触发之后加载。
该组件由父组件在导航事件中加载,如下所示:
/parent.component.ts
ngOnInit() {
this.newProposal = new Proposal;
this.newProposal.step = 1;
this.proposalStateService.emitProposal.subscribe(
data => {
this.router.navigate(['pages/proposals/new/step' + data.step]);
}
);
用户将一些数据放到该组件上,从而在该组件中触发 emitProposal,这会导致调用此方法:
private initProposal(customer, step) {
this.newProposal.first_name = customer.first_name;
this.newProposal.last_name = customer.last_name;
this.newProposal.customer_id = customer.id;
this.newProposal.email = customer.email;
this.newProposal.mobile = customer.mobile;
this.newProposal.status = 'Draft';
this.newProposal.step = step;
this.proposalStateService.pushProposal(this.newProposal);
}
看来这个“pushProposal”是在子组件加载之前触发的,这可能是问题吗?
(现在我想知道以前的日志是如何显示接收到的数据的,哈,我在写这个问题时到底改变了什么!?)
【问题讨论】:
-
您需要指定应该更新哪个控件,例如
this.myForm.patchValue({ salutation: this.salutations })或this.myForm.controls['salutation'].setValue(this.salutations). -
@jonrsharpe 谢谢。我刚刚将其添加为 D - 它也不起作用
-
在您的示例中,实际上并没有将表单绑定到 DOM 中;你需要设置
[formGroup]="myForm"。请参阅the docs 并提供minimal reproducible example。 -
@jonrsharpe 抱歉,这是一个剪切和粘贴的疏忽,现已更正。
标签: angular select angular2-forms angular2-formbuilder