【问题标题】:Angular 6: Adding @Input to component doesn't workAngular 6:将@Input 添加到组件不起作用
【发布时间】:2018-11-16 08:05:18
【问题描述】:

我一定遗漏了一些关于 @Input 的信息,因为我从 Angular CLI 收到了这个错误:

ERROR in app/web/progress/progress-button/progress-button.component.ts(10,4): Error during template compile of 'ProgressButtonComponent'
Only initialized variables and constants can be referenced in decorators because the value of this variable is needed by the template compiler in 'Input'
'Input' is not initialized at ../@angular/core/src/metadata/directives.ts(855,22).

我的模板包含这个:

<button class="btn btn-primary btn-progress"
    (click)="startProgress($event)"
    [myInput]="foobar">TEST
</button>

打字稿包含以下内容:

import { Component, OnInit } from '@angular/core';
import { Input } from '@angular/core/src/metadata/directives';

@Component({
  selector: 'app-progress-button',
  templateUrl: './progress-button.component.html',
  styles: []
})
export class ProgressButtonComponent implements OnInit {
  @Input() myInput: string;
  constructor() {}

  ngOnInit() {}

  startProgress(event) {}
}

我在这里缺少什么?

更新

根据以下建议,我相信我发现了我的错误:

&lt;app-progress-button [myInput]="'foobar'"&gt;&lt;/app-progress-button&gt;

在组件中:

<button class="btn btn-primary btn-progress"
    (click)="startProgress($event)">{{myInput}}
</button>

【问题讨论】:

  • 我不明白,你为什么在同一个组件中使用输入?你不应该在另一个组件中使用它,然后通过它的标记标签调用它,就像&lt;my-component [myInput]="'foobar'" &gt; &lt;/my-component&gt;
  • 我想你可能就在这里,我的意思是在父级中添加输入,如&lt;app-progress-button [myInput]="foobar"&gt;&lt;/app-progress-button&gt;

标签: angular angular-decorator


【解决方案1】:

如果 foobar 是一个字符串,所以添加高逗号“'foobar'”并声明 该父组件中的 Foobar。所以在父模板的html中:

应该在父母中:

<app-child [myInput]="'foobar'"> </app-child>

而且输入导入路径似乎有误,或者那里有什么特殊的东西。

【讨论】:

  • 导入路径由 VSCode 自动添加。我会编辑它。
  • 仅供参考 - 我刚刚了解到 [myInput] 中的括号会导致它需要一个表达式,因此您必须在双引号内使用单引号。由于您要传入一个字符串,因此最好使用不带括号的 并且只将 foobar 括在双引号中。见stackoverflow.com/questions/43633452/…
  • 有 50% 的把握,我猜它是一个常数。因此,当 myInput 更改时,更改检测不会重新呈现
猜你喜欢
  • 2018-12-23
  • 1970-01-01
  • 2018-11-19
  • 2019-02-27
  • 2020-07-28
  • 1970-01-01
  • 2020-11-13
  • 1970-01-01
  • 2018-12-16
相关资源
最近更新 更多