<!DOCTYPE html>
<html>

  <head>
    <base href="." />
    <script type="text/javascript" charset="utf-8">
      window.AngularVersionForThisPlunker = 'latest'
    </script>
    <title>angular playground</title>
    <link rel="stylesheet" href="style.css" />
    <script src="https://unpkg.com/core-js@2.4.1/client/shim.min.js"></script>
    <script src="https://unpkg.com/zone.js/dist/zone.js"></script>
    <script src="https://unpkg.com/zone.js/dist/long-stack-trace-zone.js"></script>
    <script src="https://unpkg.com/reflect-metadata@0.1.3/Reflect.js"></script>
    <script src="https://unpkg.com/systemjs@0.19.31/dist/system.js"></script>
    <script src="config.js"></script>
    <script>
    System.import('app')
      .catch(console.error.bind(console));
  </script>
  </head>

  <body>
    <my-app>
    loading...
  </my-app>
  </body>

</html>
/* Styles go here */

### Plunker for StackOverflow question
var angularVersion;
if(window.AngularVersionForThisPlunker === 'latest'){
  angularVersion = ''; //picks up latest
}
else {
  angularVersion = '@' + window.AngularVersionForThisPlunker;
}

System.config({
  //use typescript for compilation
  transpiler: 'typescript',
  //typescript compiler options
  typescriptOptions: {
    emitDecoratorMetadata: true
  },
  paths: {
    'npm:': 'https://unpkg.com/'
  },
  //map tells the System loader where to look for things
  map: {
    
    'app': './src',
    '@angular/core': 'npm:@angular/core'+ angularVersion + '/bundles/core.umd.js',
    '@angular/common': 'npm:@angular/common' + angularVersion + '/bundles/common.umd.js',
    '@angular/common/http': 'npm:@angular/common' + angularVersion + '/bundles/common-http.umd.js',
    '@angular/compiler': 'npm:@angular/compiler' + angularVersion  + '/bundles/compiler.umd.js',
    '@angular/platform-browser': 'npm:@angular/platform-browser' + angularVersion + '/bundles/platform-browser.umd.js',
    '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic' + angularVersion + '/bundles/platform-browser-dynamic.umd.js',
    '@angular/http': 'npm:@angular/http' + angularVersion + '/bundles/http.umd.js',
    '@angular/router': 'npm:@angular/router' + angularVersion +'/bundles/router.umd.js',
    '@angular/forms': 'npm:@angular/forms' + angularVersion + '/bundles/forms.umd.js',
    '@angular/animations': 'npm:@angular/animations' + angularVersion + '/bundles/animations.umd.js',
    '@angular/platform-browser/animations': 'npm:@angular/platform-browser' + angularVersion + '/bundles/platform-browser-animations.umd.js',
    '@angular/animations/browser': 'npm:@angular/animations' + angularVersion + '/bundles/animations-browser.umd.js',
    
    '@angular/core/testing': 'npm:@angular/core' + angularVersion + '/bundles/core-testing.umd.js',
    '@angular/common/testing': 'npm:@angular/common' + angularVersion + '/bundles/common-testing.umd.js',
    '@angular/common/http/testing': 'npm:@angular/common' + angularVersion + '/bundles/common-http-testing.umd.js',
    '@angular/compiler/testing': 'npm:@angular/compiler' + angularVersion + '/bundles/compiler-testing.umd.js',
    '@angular/platform-browser/testing': 'npm:@angular/platform-browser' + angularVersion + '/bundles/platform-browser-testing.umd.js',
    '@angular/platform-browser-dynamic/testing': 'npm:@angular/platform-browser-dynamic' + angularVersion + '/bundles/platform-browser-dynamic-testing.umd.js',
    '@angular/http/testing': 'npm:@angular/http' + angularVersion + '/bundles/http-testing.umd.js',
    '@angular/router/testing': 'npm:@angular/router' + angularVersion + '/bundles/router-testing.umd.js',
    'tslib': 'npm:tslib@1.6.1',
    'rxjs': 'npm:rxjs',
    'typescript': 'npm:typescript@2.2.1/lib/typescript.js'
  },
  //packages defines our app package
  packages: {
    app: {
      main: './main.ts',
      defaultExtension: 'ts'
    },
    rxjs: {
      defaultExtension: 'js'
    }
  }
});
//main entry point
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
import {AppModule} from './app';

platformBrowserDynamic().bootstrapModule(AppModule)
//our root app component
import {NgModule, ViewChildren, onInit, ViewChild, QueryList, Injectable, ngAfterViewInit, Component, Compiler, ViewContainerRef, ViewChild, Input, ComponentRef, ComponentFactory, ComponentFactoryResolver, ChangeDetectorRef} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'

export class ModelDataService { 
  private modelData = [];
  
  addData() {
    // Random height between 40 and 100 pixels, multiple of 10.
    // NOTE: In the real scenario, my objects don't contain a height property,
    // the dynamic height is driven by other model properties, so I don't know the height
    // until the components are rendered.
    this.modelData.push({"height": (Math.floor(Math.random() * 7) + 4) * 10 + 'px'})
  }
  
  getData() {
    return this.modelData;
  }
}

export class GeneratedDataService {
  private generatedData = [];
  
  refreshData(count) {
    // empty the array
    this.generatedData.length = 0;
    // refresh the array without losing the object reference
    Object.assign(this.generatedData, Array(count)
      .fill(0)
      .map(() => {
        return {
          'someIrelevantProperties': ''
        }
      }))
  }
  
  getData() {
    return this.generatedData;
  }
}

@Component({
  selector: 'first-cmp'
  template: `
    <li>
      <div #content class="item" [style.height]="model.height">Unknown height until rendered.</div>
    </li>`,
  styles: [
    `li {
      display: flex;
      align-items: center;
    }`,
    `.item { 
      width: 100%;
      border: 1px solid blue;
      display: flex;
      align-items: center;
      box-sizing: border-box;
      text-align: center;
      justify-content: center;
    }`
  ]
    
})
class First {
  @Input('model') model;
  @ViewChild('content') content: ElementRef;
  
  getHeight(): number {
    return this.content.nativeElement.offsetHeight;
  }
}

@Component({
  selector: 'second-cmp'
  template: `
    <li>
      <div class="item" [style.height]="height">Calculated height</div>
    </li>`,
  styles: [
    `li {
      display: flex;
      align-items: center;
    }`,
    `.item {
      width: 100%;
      border: 1px solid red;
      display: flex;
      align-items: center;
      justify-content: center;
      box-sizing: border-box;
    }`
  ]
})
class Second {
  @Input('height') height;
  @Input('model') model;
}


@Component({
  selector: 'button-cmp'
  template: `
  <button (click)="addData()" >Add data</button>
  `,
  styles: [
    `:host {width: 100%}`
  ]
})
class BtnCmp {
  
  constructor(
    private modelDataService: ModelDataService,
    private generatedDataService: GeneratedDataService
  ) {}
  
  
  addData() {
    // add some data to the left list
    this.modelDataService.addData()
    // the number of components in the second list (the right one) will always be
    // +1 higher than the number of components in the left list
    setTimeout(
      () => {
        this.generatedDataService.refreshData(this.modelDataService.getData().length + 1)
      }, 0) // <-- HERE IS THE PROBLEM. I've added the setTimeout because otherwise the
      // expected result would not be seen at all, but idealy it should work without this 'hack'.
  }
}

@Component({
  selector: 'my-app',
  template: `
  <button-cmp>Add data</button-cmp>
  <ul>
    <first-cmp *ngFor="let cmp of modelData; let i = index" [model]="cmp"></first-cmp>
  </ul>
  <ul>
    <second-cmp *ngFor="let cmp of generatedData; let i = index" [model]="cmp" [height]="calculateHeight(i)"></second-cmp>
  </ul>`,
  styles: [
    `ul {
      display: flex;
      flex-direction: column;
      width: 50%;
      box-sizing: border-box;
    }`, 
    `:host {
      display: flex;
      flex-wrap: wrap;
    }`
  ]
})
class App implements onInit {
 @ViewChildren(First) components: QueryList<First>;
 private modelData;
 private generatedData;
 
 constructor(
    private modelDataService: ModelDataService,
    private generatedDataService: GeneratedDataService
  ){}
  
 ngOnInit() {
    this.modelData = this.modelDataService.getData();
    this.generatedData = this.generatedDataService.getData();
 }
 
 calculateHeight(index: number): string {
    let renderedCmp =  this.components ? this.components.toArray() : [];
    if (renderedCmp.length === this.modelData.length) { // finished rendering the components for the list on the left
      switch (index) {
        case 0: // first
          return renderedCmp[0].getHeight() / 2 + 'px';
          break;
        case this.modelData.length: // last
          return (renderedCmp[this.modelData.length - 1].getHeight() / 2) + 'px';
          break;
        default: // in-between
          return (renderedCmp[index - 1].getHeight() + renderedCmp[index].getHeight()) / 2 + 'px'
      }
    } else {
      console.log("ngFor hasn't finished rendering yet..")
      return "20px"
    }
  }
}

@NgModule({
  imports: [ BrowserModule ],
  providers: [
    ModelDataService,
    GeneratedDataService
  ],
  declarations: [ App, First, Second, BtnCmp],
  bootstrap: [ App ]
})
export class AppModule {}