Ricardo Castañeda
Ricardo Castañeda

Reputation: 5812

Angular: How can I change the value of a property of a component inside an ngFor

Inside an ngFor I have a tabs component. To add a CSS class I use the property show which is a boolean false. If I click the component the show property toggles to true. If I click a second component I need to set false previous clicked component.

How can I access and set false the show property of the sibling components?

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>

Upvotes: 0

Views: 756

Answers (3)

Yurii Smohol
Yurii Smohol

Reputation: 19

Just write inside element)

<mat-button-toggle-group [formControl]="documentTypeControl">
  <mat-button-toggle *ngFor="let d of getDictionaryByName('DOCUMENT_TYPE')"
  [value]="d.text">{{d.text}}</mat-button-toggle>
</mat-button-toggle-group>

Upvotes: 0

ppeinado
ppeinado

Reputation: 61

I would use the index value delivered by the *ngFor, store the tab shown index and use it in the ngClass condition like this :

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>

Upvotes: 0

Anton Marinenko
Anton Marinenko

Reputation: 2992

You have to add Input() to control state in each tab.

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>

Upvotes: 1

Related Questions