Angular 2组件@Input无法正常工作

Zor*_*hgo 70 javascript typescript angular

我一直试图将属性值传递给我的组件.从我所读到的一切看起来都是正确的.但它仍然无法正常工作.我的测试值输出到屏幕,控制台为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);
    }
}
Run Code Online (Sandbox Code Playgroud)

这就是我从父页面调用组件的方式.

<TestCmp [test]='Blue32'></TestCmp>
Run Code Online (Sandbox Code Playgroud)

当页面呈现时,测试值为空.我只看到'测试价值:'.

而不是'测试值:Blue32'.

Eri*_*nez 131

你有四件事我可以注意到:

  • 您正在根组件中传递输入,这将无法正常工作.
  • 正如@alexpods所提到的,你使用的是CamelCase.你不应该.
  • 您正在传递表达式而不是字符串[test].这意味着angular2正在寻找一个名为Blue32而不是传递原始字符串的变量.
  • 您正在使用构造函数.这不起作用,它必须在视图初始化之后初始化数据绑定属性(参见OnInit的文档).

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

示例已更新为beta 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);
Run Code Online (Sandbox Code Playgroud)

请参阅此plnkr作为示例.

更新

我看到人们仍然得到了这个答案,所以我已经将plnkr更新为beta 1并且我在解释中纠正了一点:您可以访问ngAfterViewInit中的输入,但您可以在ngOnInit的生命周期中更早地访问它们.

  • 它是PascalCase,而不是camelCase. (5认同)
  • 对于其他任何人来说,解决这个问题的解决方案的部分是使用`<childcmp [test] ="'Blue32'">`而不是`<childcmp [test] ="Blue32">`(双引号) (4认同)

fgo*_*lez 12

使用双引号将字符串包围起来很简单,如下所示:

<TestCmp [test]="'Blue32'"></TestCmp>
Run Code Online (Sandbox Code Playgroud)


Mul*_*eri 6

如果使用方括号[],则Angular将使用属性绑定,并期望在引号内接收一个表达式,并且它将从组件类中查找名为“ Blue32”的属性,或在模板中查找变量。

如果要将字符串作为值传递给子组件,可以这样传递:

<child-component childProperty='passing string'></child-component>
Run Code Online (Sandbox Code Playgroud)

要么

<child-component [childProperty]="'note double quotes'"></child-component>
Run Code Online (Sandbox Code Playgroud)

然后将其放入child.component.ts中,如下所示:

import { Component, Input } from "@angular/core";

@Component({})
export class ChildComponent {

    @Input()
    childProperty: string;

}
Run Code Online (Sandbox Code Playgroud)


Cha*_*IER 5

这个角度类可以成为静态属性的技巧: ElementRef https://angular.io/docs/ts/latest/api/core/index/ElementRef-class.html

import {ElementRef} from 'angular2/core'

constructor(elementRef: ElementRef) {
    elementRef.nativeElement.getAttribute('api')
}
Run Code Online (Sandbox Code Playgroud)