模板中的angular2和formControlName值 [英] angular2 and formControlName value in template

查看:393
本文介绍了模板中的angular2和formControlName值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

哦,angular2 ...为什么这么难?

Oh angular2...why so hard?

<input type="text" formControlName="exposure" type="hidden">
<label>{{exposure}}</label>

如果我在输入中使用formControlName,则该值正确.

If I use the formControlName in the input the value is correct.

如何获取模板中的曝光值?标签中的空白

How do I get the value of exposure in template? Its blank in the label

推荐答案

formControlName指令旨在与父代一起使用 FormGroupDirective(选择器:[formGroup]).

The formControlName directive is designed to be used with a parent FormGroupDirective (selector: [formGroup]).

它接受您要FormControl实例的字符串名称 链接,并在其中查找以该名称注册的FormControl 最靠近它的FormGroupFormArray.

It accepts the string name of the FormControl instance you want to link, and will look for a FormControl registered with that name in the closest FormGroup or FormArray above it.

使用form.get('exposure').value获取控制值.

示例:

<form [formGroup]="form">
    <input type="text" formControlName="exposure" type="hidden">
    <label>{{ form.get('exposure').value }}</label>
</form>

或者

在您的组件类中,定义一个代表表单控件的getter属性:

Alternatively

In your component class, define a getter property representing your form control:

export class MyComponent {
  form = new FormGroup({
    exposure: new FormControl('')
  });

  get exposure(): FormControl { return this.form.get('exposure'); }

然后,在组件模板中,您可以引用exposure:

Then, in your component template, you can reference exposure:

<input type="text" formControlName="exposure" type="hidden">
<label>{{exposure.value}}</label>

这篇关于模板中的angular2和formControlName值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆