[英]Promise for *ngFor in Angular2
我正在使用angular2,并且尝试从*ngFor
循环内加载的元素获取.style.width
属性。 我想用它来定义其他一些元素的宽度。 这应该在页面加载时完成。 我不想在我的代码中将宽度存储为var。 我想直接从dom获得它。
诺言 :
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));
处理:
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>
当我像这样使用感冒时,它只会返回Promise was not fullfilled
未满的情况。
但是,如果我尝试itemList.children != undefined
并返回.length
,它将返回0。我缺少什么?
提前致谢!
由于id应该是唯一的而不是数组,因此getElementById
返回单个元素。 其他查询的确返回和数组(例如getElementsByClassName
或getElementsByTagName
)。
您的经理写在哪里? 它甚至可能在视图初始化之前就开始执行。 如果是这样,请尝试将其移至ngAfterViewInit
your.component.ts
import { AfterViewInit } from '@angular/core'
export class YourComponent implements AfterViewInit {
ngAfterViewInit() {
kistenPromise.then(...)
}
}
您可能要使用AfterViewInit
。 将局部变量#itemContainer
添加到您的容器中:
<div class="itemFrame" id="itemContainer" #itemContainer>
<div class="listStyle" *ngFor="let item of list">{{item}}</div>
</div>
然后在您的组件中,您可以检查该元素的子元素(或将该元素传递给另一个对其进行检查的函数):
import { ViewChild, ElementRef, AfterViewInit } from '@angular/core';
export class YourComponent implements AfterViewInit {
@ViewChild('itemContainer') itemContainer: ElementRef;
ngAfterViewInit() {
if (this.itemContainer.nativeElement.children.length) {
// ...
} else {
// ...
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.