Angular2 中的@Input() 不适用于字符串

NBM*_*NBM 3 angular

请参阅以下代码:

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 { }
Run Code Online (Sandbox Code Playgroud)

我将“HelloWorldComponent”添加到主组件(“AppComponent”)

在“app.component.html”中

<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>
Run Code Online (Sandbox Code Playgroud)

在“hello-world.component.ts”中使用@Input() 装饰器

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

}
Run Code Online (Sandbox Code Playgroud)

并在“hello-world.component.html”中

<p>
{{name}}
</p>
Run Code Online (Sandbox Code Playgroud)

为什么当我将字符串传递给 [name] 时它不起作用?

Gün*_*uer 6

你想要的是

[name]="'test'"
Run Code Online (Sandbox Code Playgroud)

或者

name="test"
Run Code Online (Sandbox Code Playgroud)

因为没有引号test被解释为标识符,而5不是(就像在普通的 TS 代码中一样)

两种变体之间的区别在于,
前者进行属性绑定,不会出现在 DOM 中,
而后者是一个普通的 HTML 属性,Angular 也会读取它。它将按原样添加到 DOM。

  • 当您添加 `[]` 时,Angular 会将值解释为表达式,而 TS/JS 中的 `test`(不带引号)表示变量 `test` 的值。`[name]="test"`(同样没有引号)意味着将组件类的字段 `test` 的名称传递给 `HelloWorldComponent` 组件的 `name` 属性。 (2认同)