【问题标题】:Input binding not working on custom made angular library输入绑定不适用于定制的角度库
【发布时间】:2020-03-04 10:15:48
【问题描述】:

我已经构建了一个 Angular 库,我可以将它导入到外部应用程序中。在我的库中存在一个名为“MainComponent”的组件,它有一个用于“objectId”的@Input 变量。

import { Component, Input } from "@angular/core";
import { Router } from "@angular/router";

@Component({
  selector: "main-component",
  templateUrl: "../templates/app.html",
  styleUrls: ["../styles/app.css"],
  providers: []
})

export class MainComponent {

  @Input() objectId: string;

  constructor() {
    console.log("MainComponent constructor running!! objectId: " + this.objectId);
    // 'objectId' is undefined in the constructor
  }
}

当我将库导入另一个项目时,我会这样使用 MainComponent:

<main-component [objectId]="123456"></main-component>

但是,objectId 始终为undefined。我不确定我做错了什么 - 由于这是一个定制的 Angular 库,我必须做些不同的事情吗?

【问题讨论】:

  • 它也是undefined in ngOnInit 和/或其他生命周期钩子吗?
  • 我对 ngAfterViewInit 进行了测试,但它仍然未定义。
  • 您可以查看this stackblitz 并尝试找出您的不同之处。
  • 另外,请注意使用[objectId]="abcdef" 会得到undefined。我们假设您实际上传递了[objectId]="123456"
  • 不,因为方括号告诉 Angular 它应该计算表达式abcdef,即undefined(除非您在组件类中定义属性abcdef)。要绑定文字字符串,可以使用objectId="abcdef"[objectId]="'abcdef'"

标签: html angular input angular7


【解决方案1】:

objectId 是一个字符串,作为输入,您可以作为任意一个传递:

<!-- use non-bracket notation to pass as string -->
<main-component objectId="123456"></main-component>

<!-- use bracket notation with single quotes to pass as string -->
<main-component [objectId]="'123456'"></main-component>

【讨论】:

  • 我认为它不会查找名称为 123456 的变量。它将评估表达式123456,这将产生相应的数字。这就是为什么原始代码应该与 123456 一起使用,而不是与 abcdef 一起使用。
【解决方案2】:

objectId 在构造函数中查询时为undefined,但如果您要实现OnInit 接口并在ngOnInit() 中查看它,则应定义它。构造组件类时不会发生输入传递,而是在生命周期的某个地方。

【讨论】:

  • 感谢您的建议,但仍未定义。
  • 您最初是否将输入作为undefined 传递并稍后切换?如果是这样,您可能需要实现 OnChanges 并检查 ngOnChanges() 中的新值
猜你喜欢
  • 2015-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多