要获取ngFor
指令的子元素长度,可以使用以下方法:
#ref
引用子元素,并使用ngAfterViewInit
钩子来获取子元素的长度。下面是一个示例:
{{ item }}
import { Component, AfterViewInit, ViewChildren, QueryList } from '@angular/core';
@Component({
selector: 'app-example',
template: `
{{ item }}
`
})
export class ExampleComponent implements AfterViewInit {
items = ['item1', 'item2', 'item3'];
@ViewChildren('childDiv') childDivs: QueryList;
ngAfterViewInit() {
console.log(this.childDivs.length); // 输出子元素的长度
}
getChildrenLength() {
console.log(this.childDivs.length); // 输出子元素的长度
}
}
ngFor
的last
变量来判断是否是最后一个子元素。下面是一个示例:
{{ item }}
import { Component } from '@angular/core';
@Component({
selector: 'app-example',
template: `
{{ item }}
`
})
export class ExampleComponent {
items = ['item1', 'item2', 'item3'];
getChildrenLength() {
const childDivs = document.querySelectorAll('div[ngFor]');
console.log(childDivs.length); // 输出子元素的长度
}
}
这些方法都可以用来获取ngFor
指令的子元素长度。选择哪种方法取决于你的具体需求和情况。