0

我已经构建了一个可以导入外部应用程序的 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 库,我必须做些什么不同的事情吗?

4

2 回答 2

2

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

于 2019-11-07T19:08:53.743 回答
2

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>
于 2019-11-07T19:50:52.143 回答