我有一个使用ng2-smart-table的网络应用。我试图检索所有单元格并将隐藏的属性应用于它们。我以为
cells = document.getElementsbyTagName("td")
在ngAfterViewInit()中可以解决这个问题,但是我认为该表尚未完成加载,因为我得到了大小为0的htmlCollection。所以我想我会尝试使用回调函数。因此,我在ngAfterViewInit()中使用了此代码(第一次使用回调函数,因此不确定这是否正确)。
let getCells = function(){
return document.getElementsByTagName("td");
}
let changeCells = function(callback){
let data = callback();
console.log(data.length);
if(data.length !== 1189){ changeCells(callback) }
else{ console.log(data.length); }
}
changeCells(getCells);
1189是多少个细胞。我知道这一点是因为我将以下代码放在ngAfterViewInit()中,它给了我该值(我期望的值)。
document.getElementById("columnButtonModal").setAttribute("href", "#columnInfoModal");
setTimeout(function(){
console.log(document.getElementsByTagName("td").length);
}, 150);
因此,在我的回调函数中,它只执行indefinitley,直到耗尽堆栈空间为止。我知道我可以使用setTimeout函数,但是我觉得那不是解决此问题的合适方法。任何帮助将不胜感激。这是我的ngOnInit()和ngAfterViewInit()代码。
ngOnInit() {
this.routingSubscription = this.route.params.subscribe(params => {
this.var = params["val"] || 'all';
this.source = new ServerDataSource(this.http, { endPoint: `webaddress` });
});
}
ngAfterViewInit(){
let getCells = function(){
return document.getElementsByTagName("td");
}
let changeCells = function(callback){
let data = callback();
console.log(data.length);
if(data.length !== 1189){ changeCells(callback) }
else{ console.log(data.length); }
}
changeCells(getCells);
/*
document.getElementById("columnButtonModal").setAttribute("href", "#columnInfoModal");
setTimeout(function(){
console.log(document.getElementsByTagName("td").length);
}, 150);
*/
}
最佳答案
问题的直接根源是递归调用。
let changeCells = function (callback) {
...
if (data.length !== 1189) { // <- The `data.length` does not become equal to 1189
changeCells(callback); // ...but the function is being recursively invoked,
// while `data` has not changed...
}
}
您要么完全不需要嵌套嵌套的递归调用,要么完全不需要嵌套的递归调用。或确保将数据调整为最终完全包含
1189
元素,否则您的代码将不断耗尽堆栈...关于javascript - 在页面加载ng2后无法获取组件的html元素,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46738261/