访问角2输入(属性)内部构造 [英] Access Angular 2 Inputs (properties) inside constructor
本文介绍了访问角2输入(属性)内部构造的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我为了学习Angular2正在创建某些组件。
我有这个基本的HTML:
< H1>测试与LT; / H1>
< BTN [为了] =0>< / BTN>
< BTN [为了] =1>< / BTN>
< BTN [为了] =2>< / BTN>
而在 TS
我有这样的:
进口{分量,输入}从'angular2 /核心;
进口{}的DataService从'../services/DataService';@零件({
选择:BTN,
模板:'<按钮和GT;测试{{}项}< /按钮>,
输入:['秩序']
})出口类ButtonComponent {
项目:数组<号取代;
项目编号;
@input()命令; 构造函数(DataService的:DataService的){
的console.log(this.order)
}
}
这样做,我得到的不确定,我究竟做错了什么?我怎么能以数据发送到类读取输入(或属性)?
修改
进口{分量,输入}从'angular2 /核心;
进口{}的DataService从'../services/DataService';@零件({
选择:BTN,
模板:'<按钮和GT;测试{{}项}< /按钮>,
输入:['秩序']
})出口类ButtonComponent {
项目:数组<号取代;
项目编号;
@input()命令; ngOnInit(DataService的:DataService的){
this.items = dataService.getItems();
的console.log(this.order)
} 构造函数(){}
}
解决方案
您不能在构造函数中访问它们,它们尚未初始化。使用 ngOnInit()
来代替。欲了解更多详情,请参见 https://angular.io/docs/ts/latest /guide/lifecycle-hooks.html
出口类ButtonComponent实现的OnInit {
项目:数组<号取代;
项目编号;
@input()命令; 构造函数(DataService的:DataService的){} ngOnInit(){
的console.log(this.order);
}
}
I'm creating some components in order to learn Angular2.
I have this basic html:
<h1>test</h1>
<btn [order]="0"></btn>
<btn [order]="1"></btn>
<btn [order]="2"></btn>
And in the ts
I have this:
import {Component, Input} from 'angular2/core';
import {DataService} from '../services/DataService';
@Component({
selector: 'btn',
template: '<button>test{{ item }}</button>',
inputs: ['order']
})
export class ButtonComponent {
items: Array<number>;
item: number;
@Input() order;
constructor(dataService: DataService) {
console.log(this.order)
}
}
Doing that I get undefined, what am I doing wrong? how can I read the inputs (or an attribute) in order to send data to the class?
EDIT
import {Component, Input} from 'angular2/core';
import {DataService} from '../services/DataService';
@Component({
selector: 'btn',
template: '<button>test{{ item }}</button>',
inputs: ['order']
})
export class ButtonComponent {
items: Array<number>;
item: number;
@Input() order;
ngOnInit(dataService: DataService) {
this.items = dataService.getItems();
console.log(this.order)
}
constructor() {}
}
解决方案
You can't access them in the constructor, they are not yet initialized. Use ngOnInit()
instead. For more details see https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html
export class ButtonComponent implements OnInit {
items: Array<number>;
item: number;
@Input() order;
constructor(dataService: DataService) { }
ngOnInit() {
console.log(this.order);
}
}
这篇关于访问角2输入(属性)内部构造的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文