2017-01-12 3 views
2

では動作しないコードは、以下を参照してください。@Input()は、文字列

import { AppComponent } from './app.component'; 
import { HelloWorldComponent } from './hello-world/hello-world.component'; 

@NgModule({ 
    declarations: [ 
    AppComponent, 
    HelloWorldComponent 
    ], 
    imports: [ 
    BrowserModule, 
    FormsModule, 
    HttpModule 
    ], 
    providers: [], 
    bootstrap: [AppComponent] 
}) 
export class AppModule { } 

私はapp.component」を主成分( 'AppComponent')

に 'HelloWorldComponent' を追加.htmlの使用@Input()デコレータ

でハローworld.component.ts '」で

<h1> 
    {{title}} 
    <app-hello-world [name]="test"></app-hello-world> // When [name]="Test" does not works but when I use number works !!! [name] = "4" 
</h1> 

'

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

@Component({ 
    selector: 'app-hello-world', 
    templateUrl: './hello-world.component.html', 
    styleUrls: ['./hello-world.component.css'] 
}) 
export class HelloWorldComponent implements OnInit { 
    @Input() name: string; 
    constructor() { } 

    ngOnInit() { 
    } 

} 

と 'ハローworld.component.html' で

<p> 
{{name}} 
</p> 

私は、[名前]に文字列をPASSAとき、それは動作しないのはなぜ? 5

差(通常のTSコードのように)ではありませんしながら、あなたが望む何

答えて

2

は、理由testは識別子として解釈され、引用符なし

[name]="'test'" 

または

name="test" 

です2つのバリアントの間にあるのは
であり、前者はプロパティバインディングを行い、表示されませんDOM
の2つ目はAngularで読み取られる通常のHTML属性です。 DOMにそのまま追加されます。

+0

TypescriptまたはAngular2のために必要な引用符はありますか? – NBM

+2

'[]'を追加するとAngularは値を式として解釈し、TS/JSの 'test'(引用符なし)は変数' test'の値を意味します。 '[name] =" test "(引用符なし)は、コンポーネントクラスのフィールド' test'の名前を 'HelloWorldComponent'コンポーネントの' name'プロパティに渡すことを意味します。 –

0

評価するロジックを参照していない場合は、Input()パラメーターの前後にかっこは必要ありません。ただ書くだけ

名前: "テスト"

+0

「ロジックを参照しない」について詳しく説明できますか? – NBM

+1

Güntherが他の答えに書いたもの。ポイントブラケットを追加すると、Angular2は引用内の任意のエクスプレッション(=ロジック)を評価します。 – Sebastian