tadaa9
tadaa9

Reputation: 523

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!

Upvotes: 41

Views: 43452

Answers (3)

m.spyratos
m.spyratos

Reputation: 4219

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.

Upvotes: 36

James Earlywine
James Earlywine

Reputation: 433

You can use underscore/lodash library. https://lodash.com/docs#merge

Just include it in your angular2/4 stack.
This question explains how: Importing lodash into angular2 + typescript application

Upvotes: 0

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657536

Angular2 doesn't provide anything like this.

You can use for example Object.assign()

Object.assign(target, source_1, ..., source_n)

Upvotes: 39

Related Questions