Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular2 and formControlName value in template

Tags:

Oh angular2...why so hard?

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

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

like image 280
Tampa Avatar asked Mar 11 '17 07:03

Tampa


People also ask

What is the difference between formControlName and FormControl?

[formControl] assigns a reference to the FormControl instance you created to the FormControlDirective . formControlName assigns a string for the forms module to look up the control by name. If you create variables for the controls, you also don't need the .

What is formControlName?

The name corresponds to a key in the parent FormGroup or FormArray . Accepts a name as a string or a number. The name in the form of a string is useful for individual forms, while the numerical form allows for form controls to be bound to indices when iterating over controls in a FormArray . @Input('disabled')

Can we give formControlName to div?

You can also create your own custom components (or directives) that can be bound to form controls—if they implement ControlValueAccessor interface. Angular has built-in ControlValueAccessor implementations for <input> , <textarea> , etc, but not for <div> .


1 Answers

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> 
like image 190
pixelbits Avatar answered Sep 23 '22 01:09

pixelbits