typescript – 使用@Inputs和s的Angular2

前端之家收集整理的这篇文章主要介绍了typescript – 使用@Inputs和s的Angular2前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我的页面中有一个子导航,在公共主视图下方显示一些子视图.我想通过< router-outlet>将对象传递给子视图.这样我就可以在主组件中检索一次数据,然后与我的子组件共享它.

注意:如果我包含指令< one>< / one>在main.html它可以工作,但这不是我想要的行为.

主要观点:

  1. <h1>Details</h1>
  2. <a [router-link]="['./sub1']">One</a> |
  3. <a [router-link]="['./sub2']">Two</a> |
  4. <a [router-link]="['./sub3']">Three</a>
  5. <hr/>
  6. <router-outlet [data]="maindata"></router-outlet>

子视图1:

  1. <h2>{{ data.name }}</h2>
  2. ...

主要观点:

  1. @Component({
  2. selector: 'main-detail',directives: [ROUTER_DIRECTIVES],templateUrl: './main.html'
  3. })
  4. @RouteConfig([
  5. { path: '/',redirectTo: '/one' },{ path: '/one',as: 'One',component: OneComponent },{ path: '/two',as: 'Two',component: TwoComponent },{ path: '/three',as: 'Three',component: ThreeComponent }
  6. ])
  7. export class MainComponent {
  8. maindata: Object = {name:'jim'};
  9. }

子视图1:

  1. @Component({
  2. selector: 'one',directives: [CORE_DIRECTIVES],inputs: ['data'],templateUrl: './one.html'
  3. })
  4. export class OneComponent {
  5. @Input() data;
  6. }
如果它是简单数据,您可以通过 RouteParams传递它们
  1. <a [router-link]="['./sub3'],{name:'jim'}">Three</a>

然后在你的子视图中

  1. @Component({
  2. selector: 'one',templateUrl: './one.html'
  3. })
  4. export class OneComponent {
  5. data: any;
  6. constructor(params: RouteParams){
  7. this.data = params.get('data');
  8. }
  9. }

您还可以设置路由以始终通过将组件中的RouterConfig移动来从组件传递参数(注意,这不是通常的方式):

  1. export class AppCmp {
  2. history: string[] = [];
  3. constructor(public list: PersonalizationList,private router_: Router) {
  4. list.get('histoy',(response) => {
  5. this.history = response;
  6. });
  7. router_.config([
  8. { path: '/',component: HomeCmp,as: 'Home',data: this.history },{ path: '/about',component: AboutCmp,as: 'About' }
  9. ]);
  10. }
  11. }

Credit to the Source

如果您打算做一些更复杂的事情,我建议使用服务在路由/组件之间进行通信.这实际上是我喜欢的方式.

样品服务:

  1. import {Injectable} from 'angular2/angular2';
  2.  
  3. @Injectable()
  4. export class CaRSService {
  5. list1: array<any> = ['a','b','c','d'];
  6. list2: array<any>;
  7.  
  8. constructor() {
  9. this.list2 = [1,2,3,9,11];
  10. }
  11. }

如何注入服务:

  1. export class Cars {
  2. constructor(cars:CaRSService) {
  3. this.cmpList1 = cars.list1;
  4. this.cmpList2 = cars.list2;
  5. }
  6. }

这样,无论父/子或其他奇怪的限制,您都可以使用该服务进行通信.

猜你在找的Angularjs相关文章