【发布时间】:2016-11-14 15:03:20
【问题描述】:
我想使用 Angular 2 创建一个动态标签导航系统。
基本上我想首先显示一个包含单个组件的单个选项卡,其中包含可点击的对象(如链接、按钮...)。
我希望单击其中一个链接会添加一个新选项卡,并且单击每个选项卡(初始选项卡和新创建的选项卡)会在下面的显示区域(路由器插座)中显示相应的组件。
这是我迄今为止尝试过的:
app.component.ts(根组件和“标签容器”):
import { Component, OnInit } from '@angular/core';
import { TabComponent } from './tab/tab.component';
import { FirstComponent } from './test/first.component';
import { SecondComponent } from './test/second.component';
import { ThirdComponent } from './test/third.component';
import { ROUTER_DIRECTIVES } from '@angular/router';
@Component({
selector: 'my-app',
templateUrl: './app/app.component.html',
directives: [TabComponent, ROUTER_DIRECTIVES, FirstComponent, SecondComponent, ThirdComponent],
})
export class AppComponent implements OnInit{
tabList: any[];
constructor() {}
ngOnInit() {
this.tabList = [
{
name: 'link 1',
link: "/comp1"
},
{
name: 'link 2',
link: "/comp2"
},
{
name: 'link 3',
link: "/comp3"
}
]
}
}
app.component.html:
<h1>Tabs container</h1>
<div>
<nav>
<tab *ngFor="let tab of tabList" [name]="tab.name" [link]="tab.link"></tab>
</nav>
</div>
<div>
<router-outlet></router-outlet>
</div>
每个选项卡都由一个 tab.component.ts 表示:
import { ROUTER_DIRECTIVES, Router } from '@angular/router';
import { Component, OnInit, Input } from '@angular/core';
@Component({
selector: 'tab',
templateUrl: './app/tab/tab.component.html',
directives: [ROUTER_DIRECTIVES]
})
export class TabComponent implements OnInit {
@Input() name: string;
@Input() link: string;
@Input() param: string;
targetArray: Array<any>;
constructor(private router: Router) {}
ngOnInit() {
}
}
tab.component.html是哪个模板:
<a [routerLink]='link'>{{name}}</a>
这里是 app.routes.ts 文件:
import { provideRouter, RouterConfig } from '@angular/router';
import { TabComponent } from './tab/tab.component';
import { FirstComponent } from './test/first.component';
import { SecondComponent } from './test/second.component';
import { ThirdComponent } from './test/third.component';
export const routes: RouterConfig = [
{
path: '',
component: TabComponent
},
{
path: 'comp1',
component: FirstComponent
},
{
path: 'comp2',
component: SecondComponent
},
{
path: 'comp3',
component: ThirdComponent
},
];
export const APP_ROUTER_PROVIDERS = [
provideRouter(routes)
];
这里以 first.component.ts 为例(SecondComponent 和 ThirdComponent 类似):
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'first',
template: `<h1>First</h1>
<button (click)="addTab()">Display child</button>
`
})
export class FirstComponent implements OnInit {
constructor() {}
ngOnInit() {
}
addTab(){
}
}
我想将选项卡创建逻辑放在 addTab() 方法中,以基本上将元素添加到 app.component.ts 中的 tabList 数组并获得所需的行为,但我不知道如何从中传输数据组件到 app.component.ts。
我也愿意接受任何不同的方法和建议。
【问题讨论】:
标签: html typescript angular components