簡體   English   中英

輸入綁定在Angular / IntelliJ中不起作用

[英]input binding not working in Angular/IntelliJ

為什么輸入綁定不起作用? 我已經采用了IntelliJ創建的框架代碼,並用我的組件my-para替換了默認的app組件。 以下是代碼段。

index.html

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

para.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 { }

我只看到“你好”,而沒有看到“你好說些什么”

如果使用方括號,它將嘗試綁定對象。 因此, <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()裝飾器,而不使用Component的input屬性。 您正在兩次定義輸入。

遵循SO解答后得到了幫助(你們也提到了一些要點)

Angular 2組件@Input無法正常工作

看來我無法在根組件中傳遞輸入。 解釋在這里-root指令上的Angular 2輸入參數

我創建了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
  ],

暫無
暫無

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

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