Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ngFor #67

Open
deepthan opened this issue Jul 27, 2020 · 0 comments
Open

ngFor #67

deepthan opened this issue Jul 27, 2020 · 0 comments

Comments

@deepthan
Copy link
Owner

*ngFor使用方法

简要写法

<div *ngFor="let book of books; 
    let i=index; 
    let isFirst=first;
    let isLast=last;
    let isEven=even;
    let isOdd=odd; 
    trackBy: trackByFunction" >
 
</div>
  • let book of books: 循环books,循环的每一项是book
  • let i=index:index是当前下标,赋值给 i, 下面的形式相同。
  • first:first:是否为第一项,赋值给isFirst
  • last: 是否为最后一项
  • even: 是否为偶数项
  • odd: 是否为奇数项

trackByFunction是一个函数,它的第一个参数是当前的index,第二个是当前的项,它需要返回一个数据,angular看它是否改变来判断这一项是否应该被重新渲染(提升性能)。

trackByFunction(index, book){
    return book.id;
}

上面表示如果id改变了则这一项会重新渲染。

还可以这样写

let i=index可以写成index as i

<div *ngFor="let book of books; 
    index as i; 
    first as isFirst;
    last as isLast;
    even as isEven;
    odd as isOdd;" >
 
</div>

或者

<ng-template ngFor let-book [ngForOf]="books" let-i="index">
  {{ book }}
</ng-template>

但是这种写法只能在ng-template上写。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant