I am trying to make dynamically tabs. So I use materialize CSS to create that in my Angular 4 App, I can't seem to get it working. I try this:
<div>
<ul class="tabs tabs-fixed-width">
<div class="indicator" style="z-index:1; background-color: #1ABFB4 !important;"></div>
<li *ngFor="let entry of data" class="tab"><a href="#{{entry.code}}">{{entry.code}}</a></li>
</ul>
</div>
<div *ngFor="let item of data" id="{{item.code}}" class="col s12">{{item.description}}</div>
</div>
This creates the tabs correctly but they don't respond with a page and every tab has all the divs, so when I have 4 tabs, I get 4 descriptions under every tab. How can I make tabs with ngFor?
//make a wrapper like below
import {
Component,
ElementRef,
AfterViewInit,
NgZone,
Input,
Output
} from '@angular/core';
declare var $: any;
@Component({
selector: 'tabs',
styles: [`
.carousel .carousel-item {
display: block; width: 200px; height:200px;
position: relative; top: 0; left: 0;
}
`],
template: `<ng-content></ng-content>`
})
export class MyTabsComponent implements AfterViewInit {
$tabs: any;
@Output() onShow: EventEmitter<any> = new EventEmitter();
@Input() swipeable = false;
constructor(private el: ElementRef, private zone: NgZone) { }
ngAfterViewInit() {
this.zone
.runOutsideAngular(() => {
this.$tabs = $(this.el.nativeElement);
this.$tabs.find('ul.tabs')
.on('click', 'a', ((tab) => {
this.zone.run(() => { // detect change and use
this.onShow.emit({ tab, tabRef: this.$tabs });
});
}).bind(this))
.tabs({// initialize your tabs outside angular
'responsiveThreshold': 1920,
'swipeable': this.swipeable
});
});
}
}
// use the wrapper component and provide the data
@Component({
select: 'app-root',
template: `
<tabs (onShow)="onTabOpen($event)>
<div>
<ul class="tabs tabs-fixed-width">
<div class="indicator" style="z-index:1; background-color:
#1ABFB4 !important;"></div>
<li *ngFor="let entry of data" class="tab"><a [attr.href]="'#'+
entry.code">{{entry.code}}</a></li>
</ul>
</div>
</tabs>
<div *ngFor="let item of data" [attr.id]="item.code" class="col s12">
{{item.description}}</div>
`
})
class AppComponent {
data: [
{
code: 'first',
description: 'I am first tab'
},
{
code: 'second',
description: 'I am second tab'
}
]
onTabOpen(event:any) {
// do some stuff
}
}
It is working for me hope it works for you as well!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.