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
你有四件事我可以注意到:
[test].这意味着angular2正在寻找一个名为Blue32而不是传递原始字符串的变量.所以有一些修复它应该工作
示例已更新为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的生命周期中更早地访问它们.
fgo*_*lez 12
使用双引号将字符串包围起来很简单,如下所示:
<TestCmp [test]="'Blue32'"></TestCmp>
Run Code Online (Sandbox Code Playgroud)
如果使用方括号[],则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)
这个角度类可以成为静态属性的技巧: 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)
| 归档时间: |
|
| 查看次数: |
71856 次 |
| 最近记录: |