Cómo lidiar con problemas de eco en formularios con estructuras anidadas multicapa en Angular

Recientemente, cuando se trataba de formas angulares, apareció una forma con una estructura de 4 capas. Y muchos elementos se generan dinámicamente, de la siguiente manera:

 this.validateForm=this.fb.group({
      storeId: ["test12"],
      storeNameKey:[''],
      config:this.fb.group({ 
          tableSize:this.fb.group({
              toggle:[false],
              groupSize:this.fb.array([
                this.fb.group({
                  cate:['indoor'],
                  title_en:[''],
                  title_zh:[''],
                  tableSize:this.fb.array([
                    this.fb.group({
                      size: [""],
                      desc_en:["small"],
                      desc_zh: ["小桌"],
                      number:['A02'],
                      preTitle: ["C"],
                      maxPerson: [8],
                      minPerson: [5],
                      alias: "S",
                    }),
                  ])
                }),
                this.fb.group({
                  cate:['outdoor'],
                  title_en:[''],
                  title_zh:[''],
                  tableSize:this.fb.array([
                    this.fb.group({
                      size: ["small"],
                      desc_en:["Small"],
                      desc_zh: ["小桌"],
                      number:['A02'],
                      preTitle: ["C"],
                      maxPerson: [8],
                      minPerson: [5],
                      alias: "S",
                    }),
                  ])
                }),
              ]),
          }),
          hasMoreTableSize:['false'],
          geoFancing:this.fb.group({
            // isOpenGeo:['true'],
            range:[100]
          }),
          dynamicQRCode:this.fb.group({
            refreshEx:[2]
          }),
          isLogin:[false],
          isShowBlockList:[false]
      }),

    })

Su interfaz se comporta de la siguiente manera:

Y cómo hacer eco de acuerdo con la estructura de datos devuelta por el backend en el estado de edición. El objeto Formbuilder en angular proporciona dos métodos: setValue y patchValue. Estos dos métodos solo son efectivos para objetos de un nivel y no pueden ser efectivos para estructuras de datos anidadas de varios niveles. Después de explorar un poco, descubrí que se puede resolver de esta manera.

Primero simule la estructura de datos del backend:

const formdata={
  storeId:"disneycart",
  storeNameKey:"123",
  config:{
    tableSize:{
      toggle:true,
      groupSize:[
        {
          cate:"indoor",
          title_en:'',
          title_zh:'',
          tableSize:[
            {
              alias: "S",
              desc_en: "small",
              desc_zh: "小4桌",
              maxPerson: 4,
              minPerson: 1,
              number: "A01",
              preTitle: "A",
              size: "small"
            },
            {
              alias: "m",
              desc_en: "middl",
              desc_zh: "中桌",
              maxPerson: 6,
              minPerson: 4,
              number: "b01",
              preTitle: "B",
              size: "middle"
            },
            {
              alias: "L",
              desc_en: "large",
              desc_zh: "中桌",
              maxPerson: 6,
              minPerson: 4,
              number: "b01",
              preTitle: "c",
              size: "large"
            },
            
          ]
        },
        {
          cate:"outdoor",
          title_en:'',
          title_zh:'',
          tableSize:[
            {
              alias: "S",
              desc_en: "small",
              desc_zh: "小4桌",
              maxPerson: 4,
              minPerson: 1,
              number: "A01",
              preTitle: "A",
              size: "small"
            },
            {
              alias: "m",
              desc_en: "middl",
              desc_zh: "中桌",
              maxPerson: 6,
              minPerson: 4,
              number: "b01",
              preTitle: "B",
              size: "middle"
            }
          ]
        }
      ]
    },
    dynamicQRCode:{
      refreshEx:200
    },
    geoFancing:{
      range:200.,
      // isOpenGeo:false
    },
    hasMoreTableSize:true,
    isLogin:true,
    isShowBlockList:true
  }    
}

Simulamos devolver los datos al front-end para que se hagan eco cuando se inicializa la página.

  ngAfterViewInit(){
    setTimeout(()=>{
      this.repatchForm(formdata)
      console.log("settimeout---后", this.validateForm)
    },2000)
  }
repatchForm(responseData:any){
    let arr2=this.resetAndGetGroupSize(responseData)            
    console.log("settimeout---前", this.validateForm)
    this.validateForm.patchValue({
      storeId: responseData.storeId,
      storeNameKey: responseData.storeNameKey,
      config: {
        tableSize: {
          toggle: responseData.config.tableSize.toggle,
          groupSize: arr2
        },
        hasMoreTableSize: responseData.config.hasMoreTableSize,
        geoFancing: {
          range: responseData.config.geoFancing.range
        },
        dynamicQRCode: {
          refreshEx: responseData.config.dynamicQRCode.refreshEx
        },
        isLogin:responseData.config.isLogin,
        isShowBlockList:responseData.config.isShowBlockList
      }
    });
  }

Tenga en cuenta que este es el núcleo: creamos un nuevo objeto formGroup y luego usamos el objeto de formulario para deshacernos del grupo original que contiene.

Finalmente, vuelva a copiar a través de patchValue. Preste especial atención aquí a que borramos el objeto groupSize original y finalmente generamos un nuevo objeto formArray atravesando los nuevos datos del backend, y finalmente reasignamos este nuevo objeto formArray a través de patchValue para que surta efecto.

//处理会显时table列表数据
  resetAndGetGroupSize(resData:any){
    let arr=resData?.config?.tableSize?.groupSize.map((group: any) => {
      return this.fb.group({
        cate: group.cate,
        title_en: group.title_en,
        title_zh: group.title_zh,
        tableSize: this.fb.array(group.tableSize.map((table: any) => {
          return this.fb.group({
            size: table.size,
            desc_en: table.desc_en,
            desc_zh: table.desc_zh,
            number: table.number,
            preTitle: table.preTitle,
            maxPerson: table.maxPerson,
            minPerson: table.minPerson,
            alias: table.alias
          });
        }))
      })
    })
    this.groupSize.clear()
    arr.forEach((item:FormGroup)=>{
      this.groupSize.push(item)
    })
    let arr2=arr.map((item:FormGroup)=>{
      return item.value
    })
    return arr2
  }

 

 

Supongo que te gusta

Origin blog.csdn.net/baidu_41601048/article/details/132759131
Recomendado
Clasificación