微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – Angular 2.将参数传递给组件

我想将一个字符串参数传递给我的组件.根据传递参数,我将为我的组件中的服务传递不同的参数.我接下来做:在index.html中调用我的组件,传递参数.
<top [mode]="tree">Loading...</top>

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

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

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

@input() mode: string;

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

console.log(this,this.mode);

组件文件的完整代码

import {Http,HTTP_PROVIDERS} from 'angular2/http';
import {Input,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
            );
    }

}

解决方法

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

因此树必须是父组件中存在的对应于字符串的东西.

如果要使用字符串树,请使用以下命令:

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

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

> Angular 2 input parameters on root directive

原文地址:https://www.jb51.cc/js/150474.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐