简体   繁体   English

是否可以从 Angular2 中的 FormControl 值访问所选对象?

[英]Is it possible to access selected object from the FormControl value in Angular2?

I'm using reactive forms for validation, so when I want to submit the form I'm using the values from the FormControl instances.我使用反应式表单进行验证,因此当我想提交表单时,我使用的是 FormControl 实例中的值。 My template looks like this:我的模板如下所示:

<select class="form-control" name="status" formControlName="status">
    <option *ngFor="let status of statuses" [ngValue]="status">
        {{status.description}}
    </option>
</select>

Status object looks like this: { id: 1, description: "desc" }状态对象如下所示: { id: 1, description: "desc" }

I would like to access to the whole status object with the value property of the FormControl ( this.form.controls.status.value ), but the selected string is stored in the value not the object.我想使用FormControl ( this.form.controls.status.value ) 的 value 属性访问整个状态对象,但所选字符串存储在值中而不是对象中。

I can access to the object when I subscribe to the valueChanges event.当我订阅 valueChanges 事件时,我可以访问该对象。 It seems a little bit illogical.似乎有点不合逻辑。 I think I should get the same value when I subscribe to the value changes and when I access to the latest value by the property of the FormControl .我认为当我订阅值更改以及通过FormControl的属性访问最新值时,我应该获得相同的值。 It makes no sense to store the latest object in my component by subscribing to the value changes event, because that would force me to duplicate the value.通过订阅 value changes 事件将最新的对象存储在我的组件中是没有意义的,因为这会迫使我复制该值。 I think this is the purpose of the form control.我想这就是表单控件的目的。 Maybe I do something wrong !?也许我做错了什么!? How can I make it work?我怎样才能让它工作?

My form was working fine in dev, but in prod it failed.我的表单在开发中运行良好,但在生产中失败了。 If you use Ahead of time compilation (AOT), then form.controls.controlName will fail.如果您使用提前编译 (AOT),则 form.controls.controlName 将失败。 You have to use form.get('controlName').您必须使用 form.get('controlName')。

Don't use control.errors?.someError, use control.hasError('someError')不要使用 control.errors?.someError,使用 control.hasError('someError')

See this link for more details:有关更多详细信息,请参阅此链接:

https://github.com/qdouble/angular-webpack2-starter#aot--donts https://github.com/qdouble/angular-webpack2-starter#aot--donts

you can use the following to see the value of your form in your html:您可以使用以下内容在 html 中查看表单的值:

form value: 
{{myForm.value | json}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM