【问题标题】:Angular 2, ngFor create a new context for each iteration?Angular 2,ngFor 为每次迭代创建一个新的上下文?
【发布时间】:2017-05-15 19:15:34
【问题描述】:

大家! 在 Angular 2 中,*ngFor 为每次迭代创建一个新的上下文?像 Angular js 中的 ng-repeat 一样?我需要更改 *ngFor 中的变量值,但该值会在所有迭代中更改。示例:

<div *ngFor="let label of labels">
    <div class="company"><a (click)="isCollapsed = !isCollapsed;isCollapsed ?                       labelStyle = {color: 'gray'}:labelStyle = {color: '#337ab7'}"                       [ngStyle]="labelStyle">{{label}}</a>
     </div>
     <div [ngbCollapse]="isCollapsed">
         <div class="item" *ngFor="let product of products">
            <div class="meta" *ngIf="product.year == label">
              <div class="details">
                <div [innerHTML]=product.reference></div>
              </div>
            </div>
         </div>
      </div>
</div>

当我点击一个标签时,isCollapsed 从 false 变为 true,但 isCollapsed 在所有迭代中都会发生变化。你能给我一个关于只点击和折叠一个标签的建议吗?

谢谢

【问题讨论】:

  • 我认为必须有一种方法来唯一地标识您要折叠的 div。如果标签始终是唯一的,也许使用 'isCollapsed + label'。
  • labelproduct 在每个上下文中发生变化,但来自外部的值(如果您从组件类访问成员,则每个上下文都相同。

标签: angular ngfor


【解决方案1】:

添加 isCollapsed 作为标签使用的类的属性。

在您的组件中,如果您的“标签”是一个数字数组,即当前是:

labels: number[]

然后改成

labels: MyLabel[]

在你的组件类之后添加一个名为 MyLabel 的模型,例如:

class MyLabel{
   constructor(public year: number, public isCollapsed: boolean){}
}

然后在 html 中你可以像这样使用它:

<div *ngFor="let label of labels">
<div class="company"><a (click)="label.isCollapsed = !label.isCollapsed                     labelStyle = {color: 'gray'}:labelStyle = {color: '#337ab7'}"                       [ngStyle]="labelStyle">{{label.year}}</a>
 </div>
 <div [ngbCollapse]="label.isCollapsed">
     <div class="item" *ngFor="let product of products">
        <div class="meta" *ngIf="product.year === label.year">
          <div class="details">
            <div [innerHTML]=product.reference></div>
          </div>
        </div>
     </div>
  </div>

【讨论】:

  • 不应该是label.isCollapsed = !label.isCollapsed吗?
【解决方案2】:

您可以在组件中使用index 名称定义一个字段并将其设置为null 并使用$index,如下所示:

<div class="company"><a (click)="toggleCollapsed($index) ? labelStyle = {color: 'gray'}:labelStyle = {color: '#337ab7'}"                       [ngStyle]="labelStyle">{{label.year}}</a>

并定义 toggleCollapsed(index) 如下:

toggleCollapsed(index : number){
    this.index != index ? this.index = index : this.index = null;
    return this.index == index;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-19
    • 1970-01-01
    • 1970-01-01
    • 2020-08-22
    • 2011-12-01
    • 2020-10-14
    • 2019-12-15
    • 2015-03-10
    相关资源
    最近更新 更多