Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 - Merging (extending) objects

How to merge 2 objects with Angular 2?

In AngularJS 1 we have the "merge" and "extend" functions: https://docs.angularjs.org/api/ng/function/angular.merge https://docs.angularjs.org/api/ng/function/angular.extend

But apparently nothing in Angular 2!

Do you have an idea?

Thanks!

like image 362
tadaa9 Avatar asked Apr 03 '16 10:04

tadaa9


2 Answers

Angular2 doesn't provide anything like this.

You can use for example Object.assign()

Object.assign(target, source_1, ..., source_n)
like image 172
Günter Zöchbauer Avatar answered Nov 19 '22 19:11

Günter Zöchbauer


The way to do it in Angular is with javascript's Object Spread syntax or Object.assign():

const obj = {...object1, ...object2}; // or
const obj = Object.assign({}, object1, object2);

The above options are not supported by IE natively.
So let's see what happens in each scenario...

 

1. Angular CLI

Version 8 and higher

In Angular CLI version 8 and higher, you don't need to take any additional actions. Applications are built using differential loading. This basically means that Angular will load a different javascript bundle for older browsers, which includes all the necessary polyfills. Read more about browser support.

Older versions

If you are using older versions of the Angular CLI with a Typescript version less than 2.1 (quite old), then open /src/polyfills.ts and uncomment the following line:

// import 'core-js/es6/object';

This will enable the Object polyfill which provides cross browser support for Object.assign().

 

2. Typescript

If you did not use Angular CLI, but you are using Typescript version 2.1 or greater, then you don't have to take any additional actions. Otherwise...

 

3. Plain Javascript

If you don't use Angular CLI or Typescript, then you can just import a polyfill into your project. There are plenty out there and here are a few ones:


Babel is a good option. You can use any of the Object.assign() and Object Spread polyfill plugins.


Another options is core-js npm package that Angular CLI uses for its polyfills.


A simple polyfill from Typescript's conversion into javascript:

Object.assign = Object.assign || function(t) {
    for (var s, i = 1, n = arguments.length; i < n; i++) {
        s = arguments[i];
        for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
            t[p] = s[p];
    }
    return t;
};

And lastly, the MDN polyfill.

like image 36
m.spyratos Avatar answered Nov 19 '22 19:11

m.spyratos