【问题标题】:Angular: How can I change the value of a property of a component inside an ngForAngular:如何更改 ngFor 中组件的属性值
【发布时间】:2021-12-25 19:18:59
【问题描述】:

在 ngFor 内部,我有一个选项卡组件。要添加 CSS 类,我使用属性 show,它是一个布尔值 false。如果我单击该组件,show 属性将切换为true。如果我单击第二个组件,我需要设置 false 上一个单击的组件。

如何访问和设置false 同级组件的show 属性?

export class TabComponent implements OnInit {
  show: Boolean = false;

  toggle(event: any) {
    this.show = !this.show;
  }
}

<ng-container *ngFor="let tab of tabs">
  <app-tab [ngClass]="show ? 'open':'closed'"  (click)="toggle($event)"></app-tab>
</ng-container>

【问题讨论】:

  • 您应该使用Boolean 和小B。并可能修复您的错误,而不是 ngClass 使用 class.show

标签: angular boolean click ngfor ng-class


【解决方案1】:

您必须添加Input() 来控制每个选项卡中的状态。

export class TabComponent implements OnInit {
  @Input()
  show: boolean = false;

  toggle(event: any) {
    this.show = !this.show;
  }
}

<ng-container *ngFor="let tab of tabs">
  <app-tab
    [show]="tab.show" // or any value you need here
    [ngClass]="tab.show ? 'open':'closed'"  
    (click)="toggle($event)">. 
  </app-tab>
</ng-container>

【讨论】:

    【解决方案2】:

    我将使用*ngFor 提供的索引值,存储选项卡显示的索引并在ngClass 条件下使用它,如下所示:

    export class TabComponent implements OnInit {
      tabShownIndex = null;
    
      toggle(index: number) {
        this.tabShownIndex = index;
      }
    }
    
    <ng-container *ngFor="let tab of tabs; let index = index;">
      <app-tab [ngClass]="index === tabShownIndex ? 'open':'closed'"  (click)="toggle(index)"></app-tab>
    </ng-container>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-12
      • 2019-01-09
      • 2016-12-13
      • 2020-11-30
      • 2019-11-27
      • 1970-01-01
      • 2011-11-29
      • 2020-02-29
      相关资源
      最近更新 更多