简体   繁体   中英

How to patch or set value for particular input field in angular reactive forms

Working on reactive nested forms where initially data is null because data is coming for some fields from the dialog box(when dialog box is closed.)

I need to set values for the particular fields of the form when data gets available without causing form reset.

This is the payload structure

data = {
  name: "", 
  imagesList: [
    {
      imagePath: "",
      imageDescription: [
        {
          language: "",
          text: ""
        }
      ]
    },
  ],
  }

Corresponding FormArray Structure for reference

在此处输入图像描述

In the below code ** openImagesDialog()** functions are receiving the data which is coming from the observable response when subscribing after dialog box is closed.

  openImagesDialog(){
    this.companyNewsDialogServiceService.imagesListDataRecieved.subscribe(res => {
      console.log("imagetest",res)
      this.modalResponseData = res
      this.imageFilePath = this.modalResponseData.data.filepath
      this.imageDescText = this.modalResponseData.data.text
      this.imageFileName = this.modalResponseData.data.filename
      console.log("imagedata", this.imageFilePath)
      console.log("imageDescText", this.imageDescText)
      this.data.imagesList.forEach(x => {
        x.imagePath = this.imageFilePath
        x.imageDescription.forEach(y => {
          y.text = this.imageDescText
        })
      })
      this.createAppForm = this.setFormGroup(this.data);
      console.log("image-form-data", this.createAppForm.value)
    })
    this.companyNewsDialogServiceService.confirmImagesListDialog({
      title: 'Images List',
      description: 'Images List Description',
      imageSrc: "",
      modalFormData: this.companyNewsDialogServiceService.recivedFormData,
      showText: true
    }); 
  }

Below code is for formation of the nested form structure as per the payload where i'm assigning setFormGroup() function to createAppForm (formgroup) like this.createAppForm = this.setFormGroup(this.data); inside the constructor

form structure code

  get imagesListFormData(){
    return <FormArray>this.createAppForm.get('imagesList')
  }

  getImageDescriptionFormData(index: number){
    return <FormArray>this.imagesListFormData.at(index).get('imageDescription');
  }
  setImageDescription(data: any = null){
    data = data || { language: null, text: null };
    return this.fb.group({
      language: [this.selectedLanguage, Validators.required],
      text: [this.imageDescText, Validators.required],
    });
  }
  setImagesList(data: any = null) {
    data = data || { assetType: null, assetLink: null, filePath: null, description: null };
    return this.fb.group({
      imagePath: [this.imageFilePath, Validators.required],
      imageDescription: this.fb.array(
        data.imageDescription
        ? data.imageDescription.map((x: any) => this.setImageDescription(x))
        : []
      )
    }
    );
  }
  setFormGroup(data: any = null) {
    // debugger
    data = data || {imagesList: null};
    return this.fb.group({
      name: [''], 
      imagesList: this.fb.array(
        data.imagesList ? data.imagesList.map((x: any) => this.setImagesList(x)): []
      )
    });
  }
  createCompanyNews(){
    const formData = this.createAppForm.getRawValue();
    console.log(formData)
    let payload = formData
    this.createCompanyNewsService.CreateCompanyNews(payload).subscribe((res: any) => {
      console.log(res)
    })
  }
  selectLanguage(language : any){
    this.selectedLanguage = language;
    console.log(this.selectedLanguage)
  }

Below code is the service file which is subcribed in ** openImagesDialog()** function to receive data from below code

export class CompanyNewsDialogServiceService {
  recivedFormData: any;
  imagesListDataRecieved: Subject<CompanyNewsDialogServiceService> = new Subject();
  constructor(private dialog : MatDialog) { }
  confirmImagesListDialog(data: ConfirmDialogData) {
    return this.dialog.open(UploadFileDialogComponent, {data}).afterClosed().subscribe(res =>{
      this.recivedFormData = res;
      console.log('formdata',this.recivedFormData)
      this.imagesListDataRecieved.next(res) ;
    });
  }
}

Currently I'm setting the form again because data is coming from dialog box which is causing loss of data entered before for name fields for the form because of form reset. I know that is wrong

I need to patch or set the value inside openImagesDialog() function to only below fields of the payload where i'm getting data for these fields inside openImagesDialog() function respectively.

Initially below these fields are null. Data for these fields are coming from dialog box after dialog box is closed.

imagePath, imageDescription -> text fields of imagesList array**

you can set the values based on payload structure what you provided inside the below function. This will not create form reset and assign values to values to respective fields only.

From next time try to simply the question this one also not concise enough to answer what you structured.

  openImagesDialog(){
    this.companyNewsDialogServiceService.imagesListDataRecieved.subscribe(res => {
      console.log("imagetest",res)
      this.modalResponseData = res
      this.imageFilePath = this.modalResponseData.data.filepath
      this.imageDescText = this.modalResponseData.data.text
      this.imageFileName = this.modalResponseData.data.filename
      let getImagesList = <FormArray>this.createAppForm.get('imagesList')
      console.log("imageListControl", getImagesList)
      console.log("image",getImagesList.value)
      getImagesList.value.forEach( (x: any) => {
        x.imagePath = this.imageFilePath
        x.imageDescription.forEach( (y: any) => {
          y.text = this.imageDescText
        })
      })
    })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM