angular2 and formControlName value in template

后端 未结 3 1139
無奈伤痛
無奈伤痛 2020-12-30 00:48

Oh angular2...why so hard?



相关标签:
3条回答
  • 2020-12-30 01:28

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

    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.

    Use form.get('exposure').value to get the control value.

    Example:

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

    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'); }
    

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

    <input type="text" formControlName="exposure" type="hidden">
    <label>{{exposure.value}}</label>
    
    0 讨论(0)
  • 2020-12-30 01:29

    In case you are looking to print the real-time values of a form in your template.

    Use

    <p>{{myForm.value|json}}</p>
    

    0 讨论(0)
  • 2020-12-30 01:33

    Declare a template variable:

    <input type="text" formControlName="exposure" type="hidden" #exposure>
    <label>{{ exposure.value }}</label>
    
    0 讨论(0)
提交回复
热议问题