How to pre-select the first tab from dynamic tabs?

I am working on an angular 4 project, I need to create a structure that has three checkboxes. A bookmark should be created dunamically after selecting the first checkbox, so by this logic, if I select all three of them, then there will be three tabs, the problem is that I am stuck on it as follows: I need at any time, one tab should be selected, so let's say if the first checkbox is selected, the first tab should be pre-selected, if the first checkbox is not selected, then you need to select the second tab. Any help in this regard would be greatly appreciated. Thanks!

For a better understanding, I created a plunker example: https://plnkr.co/edit/2UPBf67y2ExmLaePP3VV?p=preview

HTML code:

<div *ngFor="let industry of industries"> <input type="checkbox" (change)="onIndustryChange($event.target.checked, industry.id)"> <span>{{industry?.name}}</span> </div> <div class="tab-wrapper"> <ul class="nav nav-tabs app-tab-menu"> <ng-container *ngFor="let industry of industries"> <li *ngIf="isIndustrySelected(industry.id)"> <a href="#industry_{{industry.id}}" data-toggle="tab">{{industry?.name}}</a> </li> </ng-container> </ul> <div class="tab-content"> <ng-container *ngFor="let industry of industries"> <div class="tab-pane" id="industry_{{industry.id}}" *ngIf="isIndustrySelected(industry.id)"> <span>{{industry.name}}</span> </div> </ng-container> </div> 

+5
source share
1 answer

You need to check if the current index is 0, and then set the [checked] property of this parameter.

 <div *ngFor="let industry of industries; let i = index"> <input type="checkbox" [checked]="i ==0" (change)="onIndustryChange($event.target.checked, industry.id)"> <span>{{industry?.name}}</span> 

 <ul class="nav nav-tabs app-tab-menu"> <ng-container *ngFor="let industry of industries; let i = index"> <li *ngIf="isIndustrySelected(industry.id) || i == 0"> <a href="#industry_{{industry.id}}" data-toggle="tab">{{industry?.name}}</a> </li> </ng-container> </ul> 

** UPDATE **

Since this will not work according to your requirements, here is my suggestion:

  • If I'm not mistaken, the industry will come from an api call, so it will return a promise. Put this code on ngOnInit() so that html is not displayed until the data has been received. Then put the first industry index in selectedIndustries. In html, you simply add [checked]="isIndustrySelected(industry.id)" to your first div.
+2
source

Source: https://habr.com/ru/post/1272688/


All Articles