簡體   English   中英

在構造函數中訪問Angular 2輸入(屬性)

[英]Access Angular 2 Inputs (properties) inside constructor

我正在創建一些組件以學習Angular2。

我有這個基本的HTML:

<h1>test</h1>
<btn [order]="0"></btn>
<btn [order]="1"></btn>
<btn [order]="2"></btn>

ts我有這個:

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

這樣做我得到了不確定,我做錯了什么? 如何讀取輸入(或屬性)以便將數據發送到類?

編輯

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() {}
}

您無法在構造函數中訪問它們,它們尚未初始化。 請改用ngOnInit() 有關詳細信息,請參閱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);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM