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

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

主要观点:

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

子视图1:

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

主要观点:

@Component({
    SELEctor: 'main-detail',directives: [ROUTER_DIRECTIVES],templateUrl: './main.html'
})
@RouteConfig([
    { path: '/',redirectTo: '/one' },{ path: '/one',as: 'One',component: OneComponent },{ path: '/two',as: 'Two',component: TwoComponent },{ path: '/three',as: 'Three',component: ThreeComponent }
])
export class MainComponent {
    maindata: Object = {name:'jim'};
}

子视图1:

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

然后在你的子视图中

@Component({
    SELEctor: 'one',templateUrl: './one.html'
})
export class OneComponent {
    data: any;
  constructor(params: RouteParams){
    this.data = params.get('data');
  }
}

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

export class AppCmp {
  history: String[] = [];
  constructor(public list: PersonalizationList,private router_: Router) {
    list.get('histoy',(responsE) => {
      this.history = response;
    });
    router_.config([
      { path: '/',component: HomeCmp,as: 'Home',data: this.history },{ path: '/about',component: AboutCmp,as: 'About' }
    ]);
  }
}

Credit to the Source

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

样品服务:

import {InjectablE} from 'angular2/angular2';

@Injectable()
export class CaRSService {
  list1: array<any> = ['a','b','c','d'];
  list2: array<any>;

  constructor() {
    this.list2 = [1,2,3,9,11];
  }
}

如何注入服务:

export class Cars {
  constructor(cars:CaRSServicE) {
    this.cmpList1 = cars.list1;
    this.cmpList2 = cars.list2;
  }
}

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

大佬总结

以上是大佬教程为你收集整理的typescript – 使用@Inputs和s的Angular2全部内容,希望文章能够帮你解决typescript – 使用@Inputs和s的Angular2所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。