Angular——动态加载标签名和组件



在我的应用程序中,我想动态加载选项卡名称和组件.

以下JSON数据包含tab nametab links

"menu" : {
"First": "link1",
"Second": "link2",
"Third": "link3"
}

链接被配置成angular路由器文件,如下所示

const routes: Routes = [
{ path: '', component: HomeComponent},
{ path: 'link1', component: HomeComponent},
{ path: 'link2', component: UserPreferenceComponent},
{ path: 'link3', component: TableComponent },
{ path: '**', redirectTo: '' }
];

我想加载基于在JSON中配置的链接的选项卡。

<mat-tab-group>
<mat-tab label="First"> <!--Link 1 component --> </mat-tab>
<mat-tab label="Second"> <!--Link 2 component --> </mat-tab>
<mat-tab label="Third"> <!--Link 3 component --> </mat-tab>
</mat-tab-group>

Link 1组件指<app-home></app-home>

有人能告诉我如何实现这一点吗?

使用Object.entries

方法1:没有路由

app.component.html

<mat-tab-group>
<mat-tab *ngFor="let tab of obj" [label]="tab[0]">
<app-home *ngIf="tab[1] == 'link1'"></app-home>
<app-user-preference *ngIf="tab[1] == 'link2'"></app-user-preference>
<app-table *ngIf="tab[1] == 'link3'"></app-table>
</mat-tab>
</mat-tab-group>

app.component.ts

matTabs: any = {
menu: {
First: "link1",
Second: "link2",
Third: "link3"
}
};
obj: any;
constructor() {
this.obj = Object.entries(this.matTabs.menu);
}

方法2:与路由

app.component.html

<mat-tab-group (selectedTabChange)="tabChange($event)">
<mat-tab *ngFor="let tab of obj;" [label]="tab[0]">
</mat-tab>
</mat-tab-group>
<router-outlet></router-outlet>

app.component.ts

matTabs: any = {
menu: {
First: "link1",
Second: "link2",
Third: "link3"
}
};
obj: any;
constructor() {
this.obj = Object.entries(this.matTabs.menu);
}
tabChange(evt: MatTabChangeEvent) {
this.router.navigate([this.matTabs.menu[evt.tab.textLabel]]);
}

这里stackblitz例子:

https://stackblitz.com/edit/angular-mat-tab-active-xfa7n7?file=app/tabs-template-label-example.ts

希望这对你有帮助:)

你可以在你的服务中设置setter和getter函数来设置标签名和获取激活标签名

@Injectable({
providedIn: 'root'
})
export class OrderService {

activeTab: string = '';
constructor() { }

tabSetter(args: string): void {
this.activeTab = args;
}

tabGetter(): string {
return this.activeTab;
}
}
/////////// Inject the service into your component ////////
activeTab: string = '';
constructor(private service: OrderService) {
this.activeTab = this.service.tabGetter();

相关内容

  • 没有找到相关文章

最新更新