编辑变量传递到 Angular 8 Web 组件中



我用 Angular 8 创建了一个 Web 组件(我们将其命名为测试组件(,它接收输入并将其显示给浏览器(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>

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

当我在现有的角度应用程序中使用 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 元素正确显示字符串,但控制台.log是未定义的。

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

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

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

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

最新更新