2017-06-22 41 views
0

爲什麼輸入綁定不起作用?我採用了由IntelliJ創建的框架代碼,並用我的組件my-para替換了默認的app組件。以下是代碼片段。輸入綁定在Angular/IntelliJ中不起作用

的index.html

<body> 
    <my-para [paratext]="say something"></my-para> 
</body> 

paragraph.component.ts

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

@Component({ 
    selector: 'my-para', 
    inputs: ['paratext'], 
    template:` 
    <p>Hello {{this.paratext}}</p> 
    ` 
}) 

export class MyParaComponent { 
    @Input() paratext: string; 
} 

app.module.ts

import { BrowserModule } from '@angular/platform-browser'; 
import { NgModule } from '@angular/core'; 
import {MyParaComponent} from './paragraph.component' 

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

我看到的只有 「你好」,而不是「你好說點什麼「

+0

''。這個「說些什麼」的部分需要是一個字符串。但是代碼中有很多冗餘行。請按照官方文檔:https://angular.io/tutorial – echonax

+0

對不起,沒有工作 –

回答

1

如果你使用squar在括號中,它試圖綁定一個對象。 因此<my-para [paratext]="say something"></my-para>代碼查找「say something」屬性。

只需傳遞沒有括號的字符串即可。

<my-para paratext="say something"></my-para>

而且另一個節點,

在您的index.html應該只有一個應用程序組件。 使用它您app.component.html <my-para paratext="say something"></my-para>

裏面你MyParaComponent組件內,只需使用@input()組件的裝飾不輸入屬性。你正在定義你的輸入兩次。從下面的SO回答

+0

不明白你的意思是通過定義輸入兩次?如果變量被定義兩次,不會有名稱衝突嗎? –

0

得到幫助(由你們也提到了一些分)

Angular 2 Component @Input not working

看來我不能在根組件通過輸入。說明在這裏 - Angular 2 input parameters on root directive

我創建了AppComponent。然後,在AppComponent的模板,我用MyParaComponent

的index.html

<body> 
    <app-root></app-root> 
</body> 

app.component.ts

@Component({ 
    selector: 'app-root', 
    template: `<my-para [paratext]="'say something'"></my-para>` 
}) 
export class AppComponent { 
} 

app.module.ts - 不得不在聲明

同時添加AppComponent和MyParaComponent
declarations: [ 
    AppComponent, 
    MyParaComponent 
    ],