简体   繁体   中英

Promise for *ngFor in Angular2

i'm using angular2 and i'm trying to get the .style.width attribute from an element which is loaded inside a *ngFor - loop. I want to use it to define the width of some other elements. This should be done while the page loads. I dont want to store the width as some var inside my code. I want to get it directly from the dom.

promise :

let kistenPromise = new Promise(function(resolve, reject){

            let itemListContainer = document.getElementById("itemContainer");

                if(itemListContainer.children[0] != undefined){
                    resolve(itemListContainer.children);    
                }else{
                    reject(Error("Promise was not fullfilled!"));
                }
}.bind(this));

handler:

kistenPromise.then(
        function(result){
            console.log(result);
        }.bind(this), function(err){
            console.log(err);
        }.bind(this));

html:

<div class="itemFrame" id="itemContainer">
        <div class="listStyle" *ngFor="let item of list">{{item}}</div>
</div>

When i use the colde like this it only returns the Promise was not fullfilled .

However if i try itemList.children != undefined and return the .length it will return 0.What am i missing?

Thanks in advance!

getElementById returns a single element, because id should be unique, and not an array. Other queries do return and array (for example getElementsByClassName or getElementsByTagName ).

Where is your handler written? It may be getting executed before the view is even initialized. If so, try moving it to ngAfterViewInit

your.component.ts

import { AfterViewInit } from '@angular/core'
export class YourComponent implements AfterViewInit {

    ngAfterViewInit() {
        kistenPromise.then(...)

    }
}

You may want to use AfterViewInit . Add a local variable #itemContainer to your container:

<div class="itemFrame" id="itemContainer" #itemContainer>
    <div class="listStyle" *ngFor="let item of list">{{item}}</div>
</div>

Then in your component you can check the element for children (or pass the element to another function that checks for it):

import { ViewChild, ElementRef, AfterViewInit } from '@angular/core';

export class YourComponent implements AfterViewInit {
  @ViewChild('itemContainer') itemContainer: ElementRef;

  ngAfterViewInit() {
      if (this.itemContainer.nativeElement.children.length) {
          // ...
      } else {
          // ...
      }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM