Reputation: 1973
I am using bootstrap4 navs with a form I am trying to change the css class to display: none; for every tab that is not selected I have tried to make this happen by using ngClass but didn't work stackblitz demo
<ul class="nav nav-tabs" id="myTab" role="tablist">
<li class="nav-item">
<a class="nav-link active" id="itemSummary-tab" data-toggle="tab" href="#itemSummary" role="tab" aria-controls="itemSummary" aria-selected="true">Item Summary</a>
</li>
<li class="nav-item">
<a class="nav-link" id="details-tab" data-toggle="tab" href="#details" role="tab" aria-controls="details" aria-selected="false">Details</a>
</li>
<li class="nav-item">
<a class="nav-link" id="measurement-tab" data-toggle="tab" href="#measurement" role="tab" aria-controls="measurement" aria-selected="false">Measurement</a>
</li>
</ul>
<div class="tab-pane fade show active" ngClass="!active? display:none" id="itemSummary" role="tabpanel" aria-labelledby="itemSummary-tab">
....
</div>
<div class="tab-pane fade" id="measurement" ngClass="!active? display:none" role="tabpanel" aria-labelledby="measurement-tab">
...
</div>
<div class="tab-pane fade" id="details" role="tabpanel" aria-labelledby="details-tab">
...
</div>
Upvotes: 5
Views: 16879
Reputation: 17504
Try this demo code.
Created a method in ts
file as:
activateClass(tab) {
this.selectedTabName = tab;
}
and in html
<li *ngFor="let tab of tabs" (click)="activateClass(tab)" class="nav-item">
<a class="nav-link" id="{{tab}}-tab" [ngStyle]="{'background-color': (selectedTabName === tab) ? 'red' : 'black' }" data-toggle="tab" href="#{{tab}}" role="tab" >{{tab}}</a>
</li>
replace above code of [ngStyle]
, with below one to meet your requirement of display:none
[ngStyle]="{'display': (selectedTabName === tab) ? '' : 'none' }"
Not sure how will someone ever select another tab when it in display:none
state
Upvotes: 4
Reputation: 49
You can do that using conditional classes ref https://malcoded.com/posts/angular-ngclass/
Upvotes: 1
Reputation: 274
You can assign class to an element using ngClass Directive.
<p
[ngClass]="{
'red': classStyle,
'green': !classStyle}">
Dynamic classes
</p>
css
.red {
background-color: red;
}
.green {
background-color: green;
}
Upvotes: 2
Reputation: 1196
Here is from the docs https://angular.io/api/common/NgClass
<some-element [ngClass]="{'class1 class2 class3' : true}">...</some-element>
But since you are just trying to set a single style Shashank Vivek is right that you should instead try https://angular.io/api/common/NgStyle <some-element [ngStyle]="{'font-style': styleExp}">...</some-element>
Which would make your example (you need the square brackets!):
<some-element [ngStyle]="{ 'display: none': !active }">...</some-element>
This sets display: none
when active === false
Upvotes: 2