Sunday, November 26, 2017

Angular 4 Reactive Forms: Nested FormArray with Nested FormArray

This was quite the battle but I am now able to take data from a backend that has nested arrays containing nested arrays and populate nested FormArray objects. I was not able to find any blogs or StackOverflow posts that went this deep.

I refactored the Reactive Forms Heroes example. In my case I only want one hero and I want multiple addresses. The problem was that I wanted each address to have multiple pets. So, the pets are children of the addresses.

In my real-world problem, I have a questionnaire and that questionnaire has child topics and those topics have child questions.

The main meat here is in the Hero detail component and specifically the setAddresses() method. Also, the matching HTML structure in the view.

setAddresses() {
    const control = this.heroForm.controls['secretLairs']; 
    this.hero.addresses.forEach((a, i) => {
          street: a.street,
          state: a.state,
          pets: this.fb.array([])
     const petsControl = (this.heroForm.controls['secretLairs']).at(i).get('pets') as FormArray;
     a.pets.forEach(pet => {
          breed: pet.breed,
          color: pet.color

If you happen to know of a better way, please do let me know. Here's my repo:

Wednesday, April 26, 2017

ES6: Merge 2 Sorted Arrays

This is a very common coding exercise that may be asked of you when you interview for a tech company that carefully screens their candidates.

If you are going to do this similarly to the way way I do it below, you will need to understand these concepts.

  1. Array instance reduce() parameters and reduce() in general
  2. Array instance sort() parameters and sort() in general

Simply remembering the code will only take you so far. You may be asked to explain. It is a lot easier to remember something and explain it if you understand it. Memorizing might get you through a phone screen but not live coding.

Monday, March 6, 2017

Strict and Correct Equality in ES6 with

If you're targeting ES5 then you will need the polyfill. If you are noding or live in my fantasy world of targeting only ES6, then you are good to go. No need to refactor all your code yet but if you are doing extra work to deal with NaN or zeroes then you might consider it. Certainly you should use with any new code base: