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

时间:2017-01-12 07:35:03

标签: 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 { }

我将'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>

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

}

和'hello-world.component.html'

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

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

2 个答案:

答案 0 :(得分:4)

你想要的是

[name]="'test'"

name="test"

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

两种变体之间的区别在于 前者具有属性绑定功能,不会出现在DOM中 而第二个是普通的HTML属性,也由Angular读取。它将按原样添加到DOM中。

答案 1 :(得分:0)

如果您没有引用任何要评估的逻辑,则不需要Input()参数周围的尖括号。只需写下

名称= “测试”

相关问题