请看下面的代码:
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 { }
我在主要组件(“AppComponent”)中添加了“HelloWorldComponent”
在“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] 时它不起作用?
最佳答案
你想要的是
[name]="'test'"
或
name="test"
因为没有引号 test
被解释为标识符,而 5
不是(就像在普通的 TS 代码中一样)
两种变体的区别在于
前者进行属性绑定(bind),不会出现在 DOM 中
而第二个是普通的 HTML 属性,它也被 Angular 读取。它将按原样添加到 DOM。
关于angular - Angular2 中的@Input() 不适用于字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41607482/