Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the value of a FormControl in angular2

I have the following form with an FormArray containing FormGroups

 <form [formGroup]="screenForm" novalidate>

  <div formArrayName="iPhoneScreenshots" class="row">
    <div *ngIf="screenForm.controls.iPhoneScreenshots?.length > 0">
      {{screenForm.controls.iPhoneScreenshots?.length }}
      <div *ngFor="let url of screenForm.controls.iPhoneScreenshots.controls; let i=index">
        <div [formGroupName]="i">
          <input class="form-control" formControlName="url">
          <img src="{{app.screenshotUrls[i]}}" class="rounded img-fluid app-screen" style="height:200px"/>
        </div>
      </div>
    </div>
  </div>
</form>

the url values come from an array which is getting populated via API in the callback I set the values:

private setScreenShots(app: ItunesApp): void {
if (app.hasOwnProperty('screenshotUrls')) {
  const screenShots = app.screenshotUrls.map(url => {
      return this.fb.group({
        url: [url, Validators.required]
      });
    }
  );
  const screenShotsArray = this.fb.array(screenShots);
  this.screenForm.setControl('iPhoneScreenshots', screenShotsArray);
 }
}

initial array is empty

 private createForm() {
   this.appSiteForm = this.fb.group({
  title: ['', Validators.required]
});

this.screenForm = this.fb.group({
  iPhoneScreenshots: this.fb.array([]),
});

}

this code line looks very strange to me

img src="{{app.screenshotUrls[i]}}" 

I am doing this since url.value() or url.get('value') raises errors.

So how can I access the value of a form control?

like image 918
dc10 Avatar asked Apr 21 '17 13:04

dc10


People also ask

How do I find the value of FormControl?

To fetch the value of a form control, we have to use value property on the instance of FormControl in our class. In the same way we can fetch the value in HTML template.

What is a FormControl?

A form control is a user interface control that serves as the point of connection between the user and the server. Interactions vary by control type: buttons: button file handling: input type="file" menus: select , etc.


1 Answers

You can try to get control from url group

<div *ngFor="let urlGroup of screenForm.controls.iPhoneScreenshots.controls; let i=index">
    <div [formGroupName]="i">
        <input class="form-control" formControlName="url">
        <img [src]="urlGroup.get('url').value" />
    </div>
</div>

Plunker Example

like image 68
yurzui Avatar answered Oct 20 '22 10:10

yurzui