【问题标题】:Angular 2. Pass parameter to a componentAngular 2. 将参数传递给组件
【发布时间】:2016-02-22 12:10:54
【问题描述】:

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

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

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

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

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

@Input() mode: string;

并且使用 console.log() 我试图捕捉我传递的“树”参数,但它是未定义的。

console.log(this, this.mode);

一个组件文件的完整代码:

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

}

【问题讨论】:

  • 不要在你的根组件中做这些事情。它的目的只是为了保存应用程序,而不是用作组件本身。从第一个子组件开始,您将避免所有那些丑陋的变通方法。

标签: javascript typescript angular


【解决方案1】:

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

所以tree必须是父组件中存在的东西,并且对应一个字符串。

如果你想使用字符串tree,使用这个:

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

您会注意到此类参数不能用于根组件。有关详细信息,请参阅此问题:

【讨论】:

  • 你不想使用:[mode]="treee"
【解决方案2】:

作为 Thierry 解释的限制的解决方法,您可以使用

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

【讨论】:

    【解决方案3】:

    您需要等到模板绑定到 DOM。为了做到这一点,你必须实现 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);
        }
       }
    

    【讨论】:

      猜你喜欢
      • 2017-05-31
      • 2017-11-29
      • 2017-02-24
      • 1970-01-01
      • 2017-08-30
      • 2017-06-15
      • 2016-04-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多