Angular2 using @Inputs with s

前端 未结 4 943
我寻月下人不归
我寻月下人不归 2020-12-03 04:40

I have a sub-navigation in my page that displays some subviews below a common main view. I would like to pass an object to the subviews through the

4条回答
  •  臣服心动
    2020-12-03 05:07

    If it's simple data you can pass them through RouteParams

    Three
    

    then in your sub view

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

    You can also setup the route to always pass params from the component by moving the RouterConfig INSIDE the component (Note, this is not how it's normally done):

    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

    If you are going to do something more complex I suggest using a service to communicate between routes/components. It's actually the way I prefer to do it.

    Sample Service:

    import {Injectable} from 'angular2/angular2';
    
    @Injectable()
    export class CarsService {
      list1: array = ['a','b','c','d'];
      list2: array;
    
      constructor() {
        this.list2 = [1,2,3,9,11];
      }
    }
    

    How you Inject a service:

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

    This way you can use the service to communicate regardless of parent/child or other weird restrictions.

提交回复
热议问题