15

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?

2 Answers 2

17

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

Sign up to request clarification or add additional context in comments.

1 Comment

This is it. Works perfect. Can you point me to the docs since I have not seen this in the examples given on angular.io
7

Try this:

screenForm.get('url').value

1 Comment

Cannot read property 'value' of null I also updated the createForm method and you'll see that there is just another form built.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.