angulartypescriptangular2-forms

How to map properties from an angular reactive form to an object only with class member properties?


I have tried mapping reactive form properties to an object class using (Object.Assign) but it adds extra properties that doesn't belong to the class or interface, ex:

export interface MyInterface {
    a: string |null,
    b: number|null
}

and when I submit the form I do the following:

onSubmit() {
    const mynewobject:MyInterface = Object.assign({},this.myForm.getRawValue());

    console.warn(mynewobject);
  }

but the result I receive is :

{a: 'text', b: 1, c: 'additional property from form'}

I only want to map properties a and b.

Is there a way to map only properties that belong to the class or interface?


Solution

  • The most closer is iterate over the keys of the object. filter this keys by some method and use reduce to asign the variables to a new object.

    e.g.

    const obj:any={a:'fool',b:10,d:'other'}
    const obj2=Object.keys(obj).
        filter((key) => ['a','b'].includes(key)).
        reduce((cur, key) => { return Object.assign(cur, { [key]: obj[key] })}, {});
    console.log(obj2) //{a:fool,b:10}
    

    In this case you filter if the key is in the array ['a',`b']. If all the properties you need starts with some letter or you can delete some especific "keys" it's easy create the filter.

    NOTE: Remember that formgroup.value only give you the formControls not disabled, so another approach can be disable this controls.