Angular 2. Pass the parameter to the component

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

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

In my component, I include Input from angular2 / core

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

In the class of my component, I declare an input

 @Input() mode: string; 

And with console.log (), I am trying to catch my passing parameter 'tree', but it is `w90>.

 console.log(this, this.mode); 

enter image description here

Full component file code:

 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 ); } } 
+6
source share
3 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 matches the string.

If you want to use the tree string, use the following command:

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

You may notice that such parameters cannot be used for the root component . See this question for more information:

+6
source

Thierry explained that you can use

 constructor(private _participantService: ParticipantService, elRef:ElementRef) { this.mode=elRef.nativeElement.getAttribute('mode'); } 
+2
source

you need to wait until the template is bound to the DOM. for this you need to implement AfterViewInit

  export class AppTopComponent implements AfterViewInit{ public ngAfterViewInit() { console.log(this, this.mode); this.getParticipants('top3'); var self = this; setInterval(function() { self.getParticipants('top3'); }, 3000); } } 
+1
source

All Articles