@Angular2中的Input()不适用于字符串
请参阅以下代码:@Angular2中的Input()不适用于字符串,angular,Angular,请参阅以下代码: 从“/app.component”导入{AppComponent}; 从“./hello-world/hello-world.component”导入{HelloWorldComponent}; @NGD模块({ 声明:[ 应用组件, HelloWorld组件 ], 进口:[ 浏览器模块, FormsModule, HttpModule ], 提供者:[], 引导:[AppComponent] }) 导出类AppModule{} 我将“HelloWorldComponent”
从“/app.component”导入{AppComponent};
从“./hello-world/hello-world.component”导入{HelloWorldComponent};
@NGD模块({
声明:[
应用组件,
HelloWorld组件
],
进口:[
浏览器模块,
FormsModule,
HttpModule
],
提供者:[],
引导:[AppComponent]
})
导出类AppModule{}
我将“HelloWorldComponent”添加到主组件(“AppComponent”)
在“app.component.html”中
{{title}}
//当[name]=“Test”不起作用,但当我使用number时起作用!!![姓名]=“4”
在“hello world.component.ts”中使用@Input()修饰符
从'@angular/core'导入{Component,OnInit,Input};
@组成部分({
选择器:“应用程序hello world”,
templateUrl:“./hello world.component.html”,
样式URL:['./hello world.component.css']
})
导出类HelloWorldComponent实现OnInit{
@Input()名称:string;
构造函数(){}
恩戈尼尼特(){
}
}
在“helloworld.component.html”中
{{name}}
为什么当我将字符串传递到[name]时它不起作用?您想要的是
[name]="'test'"
或
因为不带引号的test
被解释为标识符,而5
则不是(与正常TS代码类似)
这两种变体之间的区别在于前者进行属性绑定,不会显示在DOM中
而第二个是一个普通的HTML属性,也是由Angular读取的。它将按原样添加到DOM中。如果未引用任何要计算的逻辑,则不需要在Input()参数周围使用尖括号。只要写
name=“test”所需的引号是因为Typescript或Angular2?当您添加
[]
Angular时,Angular将值解释为表达式,TS/JS中的test
(不带引号)表示变量test
的值[name]=“test”
(同样不带引号)表示将components类的test
字段的名称传递给HelloWorldComponent
组件的name
属性。你能解释一下关于“不引用任何逻辑”的更多信息吗?Günther在另一个答案中写道。如果添加尖括号,将使Angular2计算引号内的任何表达式(=逻辑)。
name="test"