Angular 2.将参数传递给组件

Edw*_*ard 6 javascript typescript angular

我想将一个字符串参数传递给我的组件.根据传递参数,我将为我的组件中的服务传递不同的参数.我接下来做:在index.html中调用我的组件,传递参数.

<top [mode]="tree">Loading...</top>
Run Code Online (Sandbox Code Playgroud)

在我的组件中,我包括来自angular2/core的输入

import {Input, Component, OnInit} from 'angular2/core';
Run Code Online (Sandbox Code Playgroud)

在我的组件类中,我声明了一个输入

@Input() mode: string;
Run Code Online (Sandbox Code Playgroud)

并且使用console.log()我尝试捕获'tree'的传递参数,但它未定义.

console.log(this, this.mode);
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

组件文件的完整代码:

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
            );
    }

}
Run Code Online (Sandbox Code Playgroud)

Thi*_*ier 6

使用时[...],您提供的值对应于可以计算的表达式.

所以tree必须是父组件中存在的对应于字符串的东西.

如果要使用该字符串tree,请使用:

<top mode="tree">Loading...</top>
Run Code Online (Sandbox Code Playgroud)

您可以注意到这些参数不能用于根组件.有关详细信息,请参阅此问题: