How to populate a file type input field inside a form array in Angular?

Here I have an edit form with a form array. I want to populate it with existing data. There is a drop down with four values: link,video,audio and document. If it is a link then it has to be displayed as it is where as in case of other files the choose file button populated with existing file name. Please help me.Preformatted text

import { Component, OnInit, ViewChild, QueryList, ElementRef} from '@angular/core';
import { Router } from '@angular/router';
import { ApiCallService } from 'src/app/api-call.service';
import { FormGroup, FormControl, FormArray, FormBuilder, Validators } from '@angular/forms';
import { ActivatedRoute } from '@angular/router';
import { DatePipe } from '@angular/common';

@Component({
  selector: 'app-editraining',
  templateUrl: './editraining.component.html',
  styleUrls: ['./editraining.component.scss']
})
export class EditrainingComponent implements OnInit {
 
  addedModules: FormGroup[] = [];
  moduleList: any;
  courseData: any;
  id: any;
  modulesData: any;
  file: any;
  material: any;
  type: any;
  source: any;
  duration: any;
  
   
 
  constructor(private route: Router, private apicall: ApiCallService, private fb: FormBuilder, private activatedRoute: ActivatedRoute,private datepipe:DatePipe) { }

  courseForm = new FormGroup({
    course:new FormControl(),
    department: new FormControl('', [Validators.required]),
    title: new FormControl('', [Validators.required]),
    start_date: new FormControl(),
    end_date: new FormControl(),
    description: new FormControl(),
    assessment_status: new FormControl("1"),
    timeduration: new FormControl(""),
    Mflag: new FormControl("1"),
    created_by: new FormControl("1"),
    TrainingModules: this.fb.array([], customValidateLengthArray())
  })

  TrainingModules(): FormArray {
    return this.courseForm.get("TrainingModules") as FormArray
  }

  trainingModulescon(index: string | number) {
    this.moduleList = this.courseForm.get('TrainingModules') as FormArray;
    const formGroup = this.moduleList.controls[index] as FormGroup;
    return formGroup;
  }

  trainingmodulevalid() {
    this.moduleList = this.courseForm.get('TrainingModules') as FormArray;
    return (this.moduleList.status == "VALID");
  }
  validation_modulemessage = {
    source: [{ type: 'required', message: 'Required' }],
    material: [{ type: 'required', message: 'Required' }],
    type: [{ type: 'required', message: 'Required' }],
    duration: [{ type: 'required', message: 'Required' }]
  };
   

  newModule(): FormGroup {
    return this.fb.group({
      material: new FormControl('', [Validators.required]),
      type: new FormControl('1', [Validators.required]),
      source: new FormControl('', [Validators.required]),
      duration: new FormControl('', [Validators.required])
    })
  }
  addModule() {
    this.TrainingModules().push(this.newModule());   
    
  }  

  removeModule(i: number) {
    // this.courseForm.controls["Mflag"].setValue("2");
    this.TrainingModules().removeAt(i);
  }

  get department() {
    return this.courseForm.get('department');
  }

  get title() {
    return this.courseForm.get('title');
  }

  onsubmit() {
    this.trainingmodulevalid();
    if (this.courseForm.valid) {
      //  alert(JSON.stringify(this.courseForm.value));
      this.apicall.UpdateCourse(this.courseForm.value).subscribe((res) => {
        alert("insert succesfully")
         console.log(res);
      })
    }
  }

  selectsource(event:any){
    var ids=event.target.id;
    $('.path_'+ids).removeClass('hide');
     if(event.target.value=='1'){
       $('.path_'+ids).removeClass('hide');
       $('.video_'+ids).addClass('hide');
       $('.audio_'+ids).addClass('hide');
       $('.upldoc_'+ids).addClass('hide');
     } else if(event.target.value=='2'){
       $('.video_'+ids).removeClass('hide');
       $('.path_'+ids).addClass('hide');
       $('.audio_'+ids).addClass('hide');
       $('.upldoc_'+ids).addClass('hide');
     } else if(event.target.value=='3'){
       $('.audio_'+ids).addClass('hide');
       $('.path_'+ids).addClass('hide');
       $('.video_'+ids).removeClass('hide');
       $('.upldoc_'+ids).addClass('hide');
     }else {
       $('.upldoc_'+ids).addClass('hide');
       $('.path_'+ids).addClass('hide');
       $('.video_'+ids).removeClass('hide');
       $('.audio_'+ids).addClass('hide');
     }
   }
  courseid: any;
  

  ngOnInit(): void {
    this.courseid = history.state;
  
    this.apicall.GetEmpCourseDtls(this.courseid).subscribe((res) => {
      this.courseData = res[0];
  
      // Populate the form controls with the received data
      this.courseForm.setValue({
        course: this.courseData.COURSE_ID,
        department: this.courseData.DEPARTMENT,
        title: this.courseData.TITLE,
        start_date: this.datepipe.transform(this.courseData.START_DATE, 'yyyy-MM-dd'),
        end_date: this.datepipe.transform(this.courseData.END_DATE, 'yyyy-MM-dd'),
        description: this.courseData.DESCRIPTION,
        assessment_status: JSON.stringify(this.courseData.ASSESSMENT_STATUS),
        timeduration: this.courseData.TIME_DURATION,
        Mflag: " ",
        created_by: this.courseData.CREATED_BY,
        TrainingModules: []
      });
    });
  
    this.apicall.GetEmpMaterialDtls(this.courseid).subscribe((res) => {
      this.modulesData = res;
      this.material =this.modulesData.MATERIAL_NAME;
      this.type =  this.modulesData.TYPE;              
      this.source = this.modulesData.SOURCE ,            
      this.duration = this.modulesData.TIME_DURATION          
                  

  
      
    });
  }
  
}

export function customValidateLengthArray(): Validators {
  return (formArray: FormArray): { [error: string]: any } | null => {
    if (formArray.length > 0) {
      return null;
    }
    else {
      return { error: 'Add atleast one material!' };
    }
  }
};
<!-- Left Panel -->
<app-empsidebar></app-empsidebar>
<div id="right-panel" class="right-panel">
  <app-empheader></app-empheader>
  <!-- Header -->
  <div class="content">
      <div class="animated fadeIn">         
          <div class="card">
              <div class="card-header">
                  <strong class="card-title"> Edit Course</strong>
              </div>
                <!-- {{this.courseForm.value | json}}  -->
                <!-- {{this.TrainingModule.value | json}}  -->
              <form   [formGroup]="courseForm" > 
                  <div class="row col-md-12">
                      <div class="col-md-6">
                          <!-- login id -->
                          <input type="hidden" name="created_by" id="created_by"   value="1" FormControlName="created_by">
                          
                          <input type="hidden" class="form-control Mflag"  name="Mflag" id="Mflag"   value="3" formControlName="Mflag">
                          <!-- login id -->
                          <div class="col-md-12 mt-4">
                              <div class="row form-group">
                                  <div class="col-md-3">
                                      <label for="selectSm" class="form-control-label control-label required-field">Department</label>
                                  </div>
                                  <div class="col-md-9">
                                      <!-- <input type="text" value="{{courseData.courseid}}"> -->
                                      <select name="department" id="department" class="form-control-sm form-control" formControlName="department">
                                          <option value=""selected disabled>Select Department</option>
                                          <option value="1">Manufacture</option>
                                          <option value="2">IT</option>
                                          <option value="3">HR</option>
                                          <option value="4">Purchase</option>
                                      </select>
                                      <span style="color:red;" *ngIf="department && department.invalid && department.touched ">Required</span>
                                  </div>
                              </div>
                          </div>
                          <div class="col-md-12">
                              <div class="row form-group">
                                  <div class="col col-md-3"><label for="text-input" class="form-control-label control-label required-field">Title</label></div>
                                  <div class="col-12 col-md-9">
                                      <input type="text" id="title" name="title" required  class="form-control" formControlName="title">
                                      <span style="color:red;" *ngIf="title && title.invalid && title.touched">Required</span>
                                  </div>
                              </div>
                          </div>
                          <div class="col-md-12">
                              <div class="form-group row">
                                  <label for="staticEmail" class="col-sm-3 control-label">Description</label>
                                  <div class="col-12 col-md-9">
                                      <textarea name="description" id="description" end_date rows="3" class="form-control" formControlName="description"></textarea>
                                  </div>
                              </div>
                          </div>
                      </div>
                      <div class="col-md-6">
                          <div class="col-md-12 mt-4">
                              <div class="row form-group">
                                  <div class="col col-md-3"><label for="text-input" class="form-control-label control-label">Start Date</label></div>
                                  <div class="col-12 col-md-9"><input type="date" id="start_date" name="start_date" required class="form-control" formControlName="start_date"></div>
                              </div>
                          </div>
                          <div class="col-md-12">
                              <div class="row form-group">
                                  <div class="col col-md-3"><label for="text-input" class="form-control-label control-label">End Date</label></div>
                                  <div class="col-12 col-md-9"><input type="date" id="end_date" name="end_date" required class="form-control" formControlName="end_date"></div>
                              </div>
                          </div>
                            
                          <div class="col-md-12">
                              <div class="form-group row">
                                  <label for="staticEmail" class="col-sm-3 control-label">Assessment</label>
                                  <div class="col-sm-9">
                                      <input type="radio" id="assessment_status" name="assessment_status" value="1" checked formControlName="assessment_status" >
                                      <label class="ml-1 mr-3">No</label> 
                                      <input type="radio" id="assessment_status" name="assessment_status" value="2" formControlName="assessment_status">
                                      <label class="ml-1">Yes</label>
                                  </div>
                              </div>
                          </div>
                      </div>
                      <div class="col-md-12" formArrayName="TrainingModules">
                          <div class="">
                              <div class="text-right mt-2">
                                  <button type="button" (click)="addModule()" class="btn btn-success btn-sm"><i class="fa fas fa-plus-circle"></i> Add Material</button>
                              </div>
                              <div class="table-stats ov-h">
                                  <table class="table data">
                                      <thead>
                                          <tr>
                                              <th scope="col" class="tb_font_sty">Material Name</th>
                                              <th scope="col" class="tb_font_sty">Material Type</th>
                                              <th scope="col" class="tb_font_sty">Source</th>
                                              <th scope="col" class="tb_font_sty">Duration(in min)</th>
                                              <th scope="col" class="tb_font_sty"></th>
                                          </tr>
                                      </thead>
                                      <tbody>
                                          <tr *ngFor="let TrainingModule of TrainingModules().controls; let i=index" [formGroupName]="i">
                                              <!-- <input type="text" name="index" value="{{i+1}}"> -->
                                              <td scope="row "><input type="text" name="material" value="{{material}}"    class="form-control form-control-sm" formControlName="material"[ngClass]="{'is-invalid':
                                                  trainingModulescon(i).controls['material'].errors && (trainingModulescon(i).controls['material'].dirty || trainingModulescon(i).controls['material'].touched)}">
                                              
                                                  <div *ngFor="let validation of validation_modulemessage.material"  class="invalid-feedback">
                                                      <div  *ngIf="trainingModulescon(i).controls['material'].hasError(validation.type) && (trainingModulescon(i).controls['material'].dirty || trainingModulescon(i).controls['material'].touched)">
                                                      {{ validation.message }} 
                                                      </div> 
                                                  </div>
                                              </td>
                                              <td class="">
                                                  <select name="type" id="{{i}}" class="form-control form-control-sm" formControlName="type" (change)="selectsource($event)" [ngClass]="{'is-invalid':
                                                    trainingModulescon(i).controls['type'].errors && (trainingModulescon(i).controls['type'].dirty || trainingModulescon(i).controls['type'].touched)}">
                                                      <option value="" selected disabled>Select Source</option>
                                                      <option value="1">Link</option>
                                                      <option value="2">Video</option>
                                                      <option value="3">Audio</option>
                                                      <option value="4">Document</option>
                                                  </select>
                                                   
                                                  <div *ngFor="let validation of validation_modulemessage.type"  class="invalid-feedback">
                                                      <div  *ngIf="trainingModulescon(i).controls['type'].hasError(validation.type) && (trainingModulescon(i).controls['type'].dirty || trainingModulescon(i).controls['type'].touched)">
                                                          {{ validation.message }} 
                                                      </div> 
                                                      
                                                  </div>
                                              </td> 

                                                 <td class="path_{{i}}">
                                                  <!-- <ng-container [ngSwitch]="trainingModulescon(i).controls['type'].value"> -->
                                                    <!-- Show link for material type '1' (Link)
 -->
                                                    <!-- <ng-container *ngSwitchCase="'1'"> -->
                                                      <!-- <a [href]="trainingModulescon(i).controls['source'].value">{{ trainingModulescon(i).controls['source'].value }}</a> -->
                                                      <input type="text"class="form-control form-control-sm" name="source" formControlName="source" [ngClass]="{'is-invalid':
                                                      trainingModulescon(i).controls['source'].errors && (trainingModulescon(i).controls['source'].dirty || trainingModulescon(i).controls['source'].touched)}">
                                                    
                                                    <div *ngFor="let validation of validation_modulemessage.source"  class="invalid-feedback">
                                                        <div  *ngIf="trainingModulescon(i).controls['source'].hasError(validation.type) && (trainingModulescon(i).controls['source'].dirty || trainingModulescon(i).controls['source'].touched)">
                                                        {{ validation.message }} 
                                                        </div> 
                                                    </div>
                                                    
                                                    <!-- </ng-container> -->
                                                    
                                                    <!-- <ng-container *ngSwitchDefault>
                                                        <input type="file" formControlName="source" name="source" (change)="hideSpan()"[class.hidden]="hideInput">
                                                        
                                                        <span class="source" *ngIf="showSpan">{{ modulesData[i]['SOURCE'] }}</span>
                                                       
                                                                                                                
                                                        
                                                      </ng-container> -->
                                                      
                                                  <!-- </ng-container> -->
                                                  </td>
                                                
                                                  <!-- *ngIf="trainingModulescon(i).controls['source'].value" -->
                                                  <!-- (change)="handleFileChange($event)" -->


                                              
                                                
                                                   <td class="path_{{i}}">   
                                                   <input type="text"class="form-control form-control-sm" name="source" formControlName="source" [ngClass]="{'is-invalid':
                                                    trainingModulescon(i).controls['source'].errors && (trainingModulescon(i).controls['source'].dirty || trainingModulescon(i).controls['source'].touched)}">
                                                  
                                                  <div *ngFor="let validation of validation_modulemessage.source"  class="invalid-feedback">
                                                      <div  *ngIf="trainingModulescon(i).controls['source'].hasError(validation.type) && (trainingModulescon(i).controls['source'].dirty || trainingModulescon(i).controls['source'].touched)">
                                                      {{ validation.message }} 
                                                      </div> 
                                                  </div>
                                              </td>
                                              <td class="video_{{i}} hide">
                                                  <input type="file"  formControlName="source" name="source"> 
                                                  <!-- <div>{{modulesData.SOURCE}}</div> -->
                                               </td>  
                                              <!-- <td class="audio_{{i}} hide">
                                                  <input type="file"    formControlName="source" name="source"> -->
                                                  <!-- style="width: 95px;" -->
                                              <!-- </td> -->
                                              <!-- <td class="upldoc_{{i}} hide">
                                                  <input type="file" formControlName="source" name="source">
                                              </td> -->
                                              <td class="">
                                                  <input type="text"  name="duration" class="form-control form-control-sm"  formControlName="duration" [ngClass]="{'is-invalid':trainingModulescon(i).controls['duration'].errors && (trainingModulescon(i).controls['duration'].dirty || trainingModulescon(i).controls['duration'].touched)}">
                                          
                                                  <div *ngFor="let validation of validation_modulemessage.duration"  class="invalid-feedback">
                                                      <div  *ngIf="trainingModulescon(i).controls['duration'].hasError(validation.type) && (trainingModulescon(i).controls['duration'].dirty || trainingModulescon(i).controls['duration'].touched)">
                                                      {{ validation.message }} 
                                                      </div> 
                                                  </div>
                                              </td>       
                                              <td>
                                                  <button class="btn btn-danger btn-sm" (click)="removeModule(i)"><i class="fa fa-trash" aria-hidden="true"></i></button>
                                              </td>
                                          </tr>
                                      </tbody>
                                  </table>
                              </div>
                          </div>
                      </div>
                  </div>
                  <div class="col-md-12 mt-4">
                      <div class="mb-2" align="right">
                          <button type="submit" class="btn btn-outline-success mr-1" (click)="onsubmit()" 
                            [disabled]="(courseForm.controls['department'].invalid || courseForm.controls['title'].invalid) || !trainingmodulevalid() || courseForm.invalid ">Submit</button>
                          <button type="reset" class="btn btn-outline-danger">Reset</button>
                      </div>
                  </div>
              </form>
          </div>
      </div>
      <div class="clearfix"></div>
    <!-- Footer -->
    <app-empfooter></app-empfooter>
    <!-- Footer -->
  </div>
<!-- Right Panel -->
![Screenshot 2023-05-04 204824|690x263](upload://jWXF04bjfJhTultiwp7sv1yQgS8.png)

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.