我有一个与Angular 2 模型驱动表单中的下拉列表中描述的问题类似的问题(尽管模型绑定到选择框要简单得多)。
模板非常简单,基本上是一个“亲爱的 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”是在子组件加载之前触发的,这可能是问题吗?
(现在我想知道以前的日志是如何显示接收到的数据的,哈,写这个问题时我到底改变了什么!?)
