角2组件@input不工作 [英] Angular 2 Component @Input not working

查看:156
本文介绍了角2组件@input不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我被困在试图将属性值传递到我的组件。从我读过的一切看起来是正确的。但它仍然没有工作。我的测试值获取输出到屏幕和控制台为空。 (

I am stuck on trying to pass a property value into my component. From what I've read everything looks correct. But it is still not working. My test value gets output to the screen and the console as null. :(

这是我的测试组件:

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

@Component({
    selector: 'TestCmp',
    template: `Test Value : {{test}}`
})

export class TestCmp {

    @Input() test: string;

    constructor()
    {
        console.log('This if the value for user-id: ' + this.test);
    }
}

这是我如何打电话从父页面的组件。

This is how I am calling the component from the parent page.

<TestCmp [test]='Blue32'></TestCmp>

在页面渲染的测试值是空的。我只看到'测试值:

When the page render's the test value is empty. I only see 'Test Value :'.

而不是测试值:Blue32。

Instead of 'Test Value : Blue32'.

在先进的感谢!

推荐答案

您有四样东西,我可以注意:

You have four things that I can note :


  • 您正在传递一个输入根组件,这是行不通的。

  • 作为@alexpods提到的,您使用的是驼峰。你不应该。

  • 您是通过传递一个前pression而不是字符串[测试] 。这意味着,angular2正在寻找 Blue32 名为变量,而不是通过一个原始字符串。

  • 您正在使用的构造函数。这是行不通的,它必须是观点已被初始化后,数据绑定属性已初始化(见的OnInit )。

  • You are passing an input in the root component, which will not work.
  • As @alexpods mentioned, you are using CamelCase. You should not.
  • You are passing an expression instead of an string through [test]. That means that angular2 is looking for a variable named Blue32 instead of passing a raw string.
  • You are using the constructor. That will not work, it must be after the view has been initialized data-bound properties have been initialized (see docs for OnInit).

所以有一些修正它应该工作

So with a few fixes it should work

示例更新到公测1

import {Component, Input} from 'angular2/core';
import {bootstrap} from 'angular2/platform/browser';

@Component({
  selector : 'childcmp',
  template: `Test Value : {{test}}`
})
class ChildCmp {
    @Input() test: string;
    ngOnInit() {
        console.log('This if the value for user-id: ' + this.test);
    }
}

@Component({
    selector: 'testcmp',
    template : `<childcmp [test]="'Blue32'"></childcmp>`
    directives : [ChildCmp]
})
export class TestCmp {}

bootstrap(TestCmp);

请参阅此 plnkr 作为一个例子。

See this plnkr as an example.

我看到人们仍然达到这个答案,所以我已经更新了plnkr来测试1和纠正我的解释一点:您可以访问输入在ngAfterViewInit,但你可以在中ngOnInit生命周期的早期访问它们。

I see that people still reach this answer, so I've updated the plnkr to beta 1 and I corrected one point on the explanation : You can access inputs in ngAfterViewInit, but you can access them earlier in the lifecycle within ngOnInit.

这篇关于角2组件@input不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆