Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2. Pass parameter to a component

I would like to pass a string parameter to my component. Depending on passing parameter i will pass different parameters for services in my component. I do next: In index.html call my component, passing parameter.

<top [mode]="tree">Loading...</top>

In my component i include Input from angular2/core

import {Input, Component, OnInit} from 'angular2/core';

In my component`s class i declare an input

@Input() mode: string;

And with console.log() i try to catch my passing parameter of 'tree', but it`s undefined.

console.log(this, this.mode);

enter image description here

The full code of a component file:

import {Http, HTTP_PROVIDERS} from 'angular2/http';
import {Input, Component, OnInit} from 'angular2/core';
import {ParticipantService} from '../services/participant.service';
import {orderBy} from '../pipes/orderby.pipe';

@Component({
    selector: 'top',
    templateUrl: 'dev/templates/top.html',
    pipes: [orderBy],
    providers: [HTTP_PROVIDERS, ParticipantService]
})
export class AppTopComponent implements OnInit {

    constructor (private _participantService: ParticipantService) {}

    errorMessage: string;
    participants: any[];
    @Input() mode: string;

    ngOnInit() {
        console.log(this, this.mode);
        this.getParticipants('top3');
        var self = this;
        setInterval(function() {
            self.getParticipants('top3');
        }, 3000);
    }

    getParticipants(public mode: string) {
        this._participantService.getParticipants(mode)
            .then(
                participants => this.participants = participants,
                error => this.errorMessage = <any>error
            );
    }

}
like image 259
Edward Avatar asked Feb 22 '16 12:02

Edward


2 Answers

When you use [...], the value you provide corresponds to an expression that can be evaluated.

So tree must be something that exists in the parent component and correspond to a string.

If you want to use the string tree, use this:

<top mode="tree">Loading...</top>

You can notice that such parameters can't be used for root component. See this question for more details:

  • Angular 2 input parameters on root directive
like image 118
Thierry Templier Avatar answered Oct 22 '22 06:10

Thierry Templier


As a workaround for the limitation Thierry explained you can use

constructor(private _participantService: ParticipantService, 
    elRef:ElementRef) {
  this.mode=elRef.nativeElement.getAttribute('mode');
}
like image 32
Günter Zöchbauer Avatar answered Oct 22 '22 08:10

Günter Zöchbauer