编辑传递给 Angular 8 Web 组件的变量

Edit variable passed into an Angular 8 Web component

我创建了一个 Web 组件(我们将其命名为测试组件),其中 Angular 8 接收输入并将其显示给浏览器(test.component.html 文件)

<h3>{{title}}</h3>

test.component.ts 文件接收输入并将其记录在控制台中

export class TestComponent implements OnInit {
  @input() title;

  constructor() {}
  ngOnInit() {console.log(this.title)}
}

使用 Web 组件的独立应用程序的 index.html 如下所示:

<test-component title="this is a string"></test-component>

它正确显示字符串并将其记录到控制台。

当我在现有 angular 应用程序中使用 Web 组件时出现问题。我想传递给 Web 组件的变量是动态的,来自现有应用程序的组件。我尝试以两种不同的方式将它传递到一个已经存在的组件中(例如 existing-application.component.html):

<test-component [title]="titleVariable"></test-component>

<test-component title={{titleVariable}}></test-component>

其中 titleVariable 在关联的 existing-application.component.html 文件中定义如下

export class ExistingApplicationComponent implements OnInit {

  titleVariable= 'this is a string';

  constructor() {}
  ngOnInit() {}
}

此处,虽然 h1 html 元素正确显示字符串,但 console.log 未定义。

我也曾尝试将它(在 Web 组件中)记录在 ngAfterViewInit() 而不是 ngOnInit() 中,但没有任何运气。

有人知道为什么会发生这种情况吗? 提前感谢您的宝贵时间

问题出在生命周期挂钩上。当您想要访问 input() 属性时,您需要 ngOnChanges() 生命周期挂钩。

NgOnChanges: "在 Angular(重新)设置数据绑定输入属性时响应。该方法接收当前和先前 属性 值的 SimpleChanges 对象。 在 ngOnInit() 之前以及每当一个或多个数据绑定输入属性更改时调用。 “