2016-08-27 37 views
0

我有以下簡單的角2的應用: app.component.ts角2 RC5 ngStyle數據不從父組件傳播

import { Component } from '@angular/core'; 

@Component({ 
    selector: 'my-app', 
    template: ` 
     <h1>Test</h1> 
     <test-component [Height] = "300" [Width]="300"></test-component>` 
}) 
export class AppComponent { 

    public constructor() {} 
} 

和實際測試部件:

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

@Component({ 
    selector: 'test-component', 
    template: ` 
    <div [ngStyle]="{'height' : Height + 'px', 'width' : Width + 'px'}"></div> 
    ` 
}) 
export class TestComponent implements OnInit { 
    @Input() Height : any; 
    @Input() Width : any; 

    constructor() { } 

    ngOnInit() { } 

} 

然而,ngStyle數據不會傳播到測試組件。我做錯了什麼或在RC5中破壞了?

謝謝

+0

做工精細這裏:http://plnkr.co/edit/owlvg94BINLcOHoNCyKC –

回答

1

您還沒有將TestComponent作爲指令聲明。

你必須爲了工作宣告它作爲一個AppComponent指令。您的代碼應該是這樣的AppComponent類:

import { Component } from "@angular/core"; 
import {TestComponent} from "./test.component"; 

@Component({ 
    selector: "app", 
    directives: [TestComponent], 
    template: `<div>{{message}}</div> 
    <test-component [Height] = "500" [Width]="300"></test-component>` 
}) 
export class AppComponent { 
    public constructor() {} 
} 

傳遞TestComponentComponent裝飾的directives財產。

工作花掉here

更新

由於@JB Nizet正確地指出,在組件層次上聲明的指示標記棄用,並將從2.0.0正式版中移除,以有利於使用NgModules的作爲宣佈你的指示的地方。 你可以參考Angular2 Blog以獲得更多信息。

在一個新的和更新普拉克,我已經更新了代碼,這樣你就聲明對NgModule你的指令。

NgModule

import { NgModule }  from '@angular/core'; 
import { BrowserModule } from '@angular/platform-browser'; 
import { AppComponent } from './app.component'; 
import {TestComponent} from "./test.component"; 

@NgModule({ 
    imports:  [ BrowserModule ], 
    declarations: [ AppComponent, TestComponent ], 
    bootstrap: [ AppComponent ] 
}) 
export class AppModule { } 

Component

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

@Component({ 
    selector: "app", 
    template: `<div>{{message}}</div> 
    <test-component [Height] = "500" [Width]="300"></test-component>` 
}) 
export class AppComponent { 

} 
+0

這是RC5之前如此。由於RC5,指令已被棄用,並且指令必須在NgModule中聲明。 –

+0

@JBNizet相應地更新了答案。只需要指出,在RC5中,在組件級別聲明指令就可以了,但它會在2.0.0-final版本中被刪除。感謝您指出。 – gdyrrahitis