Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 passing object to component

I'm trying to pass an object to another component.

Request-list.html

<tr [routerLink]="['Request', { id: request.id }]" *ngFor="let request of requests" [req]="request">
                        <td class=" ">{{ request.datum }}</td>
                        <td class=" ">{{ request.artist.name }} </td>
                        <td class=" ">{{ request.artist.user.first_name }}
                        <td class=" ">{{ request.user.first_name }}</td>
                        <td class=" ">{{ request.duration.price }}</td>
                        <td class=" ">{{ request.created_at }}</td>
                        <td class=" ">{{ request.rejected_at }}</td>
                    </tr>

RequestListComponent

import {Component} from '@angular/core';
import {Service} from './../services/service.service';
import {Request} from './../classes/request';
import {RouteConfig, ROUTER_DIRECTIVES} from '@angular/router-deprecated';
import {RequestComponent} from './request.component';

@Component({
  directives: [ROUTER_DIRECTIVES, RequestComponent],
  templateUrl: 'partials/request-list.html'
})

export class RequestListComponent {
  requests: Request[];
  constructor(private _Service: Service) {}

  ngOnInit(){
    this._Service.getRequests().subscribe(data => this.requests = data);
  }
}

RequestComponent

import {Component, Input} from '@angular/core';
import {Service} from './../services/service.service';
import {Request} from './../classes/request';


@Component({
  templateUrl: 'partials/request.html'
})

export class RequestComponent {
  @Input() req: Request;

  constructor(private _Service: Service) {}
}

However I get the error: "Can't bind to 'req' since it isn't a known native property"

What am I doing wrong?

like image 575
Ruben Avatar asked Feb 16 '26 08:02

Ruben


1 Answers

As I mentioned in my comment, you cannot use @Input() if your RequestComponent is loaded with the Router. Unfortunately it is not possible to pass RouteData with the RouteLink-Directive.

To solve this problem, I would load the Request inside the RequestComponent from the service, which you used to load the list of Requests. To reduce the traffic to a backend, if you have one, you can build some caching mechanism.

export class RequestComponent {
    req: Request;

    constructor(private _Service: Service, routeParams : RouteParams) {
        this.req = _Service.getRequestById(routeParams.get('id'));
    }
}
like image 82
Dinistro Avatar answered Feb 19 '26 00:02

Dinistro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!