[英]Creating Link Component in Angular2
希望在Angular 2中创建包装器组件,类似于react-bootstrap和其他工具允许您创建包装器组件的方式。 希望能够重用该组件,因此我们不必每次都重复该结构。
本质上,我希望能够重用具有这种粗略结构的组件:
'use strict';
import { ROUTER_DIRECTIVES, ROUTER_PROVIDERS } from 'angular2/router';
import {Component, Input} from 'angular2/core';
@Component({
selector: 'nav-item',
directives: [ROUTER_DIRECTIVES],
providers: [ROUTER_PROVIDERS],
template: `
<li>
<a routerLink="<SPECIFIED ROUTE>">
<ng-content></ng-content>
</a>
</li>
`,
})
export default class NavLink {
public static $injector: Array<string> = [];
@Input() to: string;
constructor() {}
}
接着
'use strict';
import {Component} from 'angular2/core';
import NavLink from './link.component';
@Component({
selector: 'Navbar',
host: {'class': 'navbar'},
directives: [NavLink],
template: `
<div class="row">
<ul>
<nav-item to="/Foo">
</nav-item>
</ul>
</div>
`,
})
export default class Nav {
constructor() {}
}
我知道routerLink期望使用数组规范,但是我想知道将数据从父组件传递到子组件然后在子组件中访问该数据的angular2方法是什么。 我知道@Input装饰器可以让您指定要传入的属性,然后可以使用父组件中的[]绑定到该属性,但是我不确定组件中的最佳访问方法:)
我试过了:
<a routerLink="{{ to }}">
但是angular2抱怨无法.forEach
超出预期的数组规范(这很有意义)。
EXCEPTION: TypeError: linkParams.forEach is not a function in [{{ to }} in NavLink@2:8]
我只是不确定将数据传递到绑定属性的方式。 我来自React的更多背景,所以事情都是通过props
传递的,您可以检查类型,这几乎只是普通的JavaScript对象传递。
访问绑定属性的最佳方式是什么,并且/或者这是我要实现的反模式?
我认为Angular2组件是React组件的更强大的版本,您可以花更少的钱做更多的事情。 我不确定这是好是坏,但是只是知道您可能不需要抽象那么多的东西,或者想要像在React中那样抽象那么多的东西。 这是因为有更多的预构建工具,这些工具可能又使您执行某些操作的自由度降低,并使其更快地执行其他操作。
我还要说,至少对我而言,在React中来回传递值更加直观。
因此,在这里继续介绍正确的语法以及路由在Angular2中的工作方式。 尽管您可能已经知道了这一点,但无论如何我都会将其发布,以防其他人阅读。
您将从一个@RouteConfig装饰器开始,该装饰器接受一组对象并将其提供给您的应用程序。 因此,您的情况如下:
@RouteConfig([
{path: '/wine', name: 'Wine', component: Wine},
//or just so you can see it in case you haven't how to add params!
{path: '/wine/:type', name: 'WineType', component: WineType}
])
现在要访问routerlink,您将通过它:
<a [routerLink] = "['/Wine'] </a>
<a [routerLink] = "['/WineType', {type: type.ID}]}> </a>
现在回答您的来回传递问题。
对于第一个组件,应输入以下内容:
<li>
<a routerLink="[to]">
<ng-content></ng-content>
</a>
</li>
因此,您很可能希望将to字符串括在方括号中,以便语法对于routerLink而言是正确的。
对于第二个组件Navbar,语法相当接近,但不完全精确。
<div class="row">
<ul>
<nav-item [to]="/Wines"></nav-item>
</ul>
</div>
这表示将“ / Wines”传递到子组件中的变量[to]。 它必须放在方括号中。
并添加导航栏项目列表,您可以执行以下操作:
'use strict';
import {Component} from 'angular2/core';
import NavLink from './link.component';
@Component({
selector: 'Navbar',
host: {'class': 'navbar'},
directives: [NavLink],
template: `
<div class="row">
<ul>
<nav-item *ngFor="#item of items [to]=item>
</nav-item>
</ul>
</div>
`,
})
export default class Nav {
all_my_routes: Array<string> = [];
constructor() {
all_my_routes = ['/Wine', '/OtherWine', '/Beer']
}
}
哪个应该遍历您的Nav项目。
另外一个侧面并不是因为我认为这是一个有点愚蠢的关键字,它仍然让我的时间约50%,为确保您使用of
你之间ngFor #item of items
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.