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

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

我在主要组件(“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/

相关文章:

javascript - angular2 组件生命周期

angular - 如何同时实现 Laravel 5.5 和 Angular 4 项目?

Angular 2初始加载进度

带有文本区域的 Angular 表单

http - Angular 2 : Rendering data from Observables

angular - (任何窗口).global = window;

node.js - Passportjs req.isAuthenticated 始终显示 false

html - 具有向下钻取功能的 Angular 5 表

angular - 应用程序模块提供程序抛出 NullInjectorError : No provider for InjectionToken MSAL_GUARD_CONFIG

angular - 转换枚举结构值:key to key:value in TypeScript