【发布时间】:2020-01-08 14:08:05
【问题描述】:
我使用 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>
它正确显示字符串并将其记录到控制台。
当我在现有的 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() 中,但没有任何运气。
有人知道为什么会发生这种情况吗? 提前感谢您的宝贵时间
【问题讨论】:
-
这能回答你的问题吗:stackoverflow.com/questions/34396684/…
-
非常感谢@Layera,虽然它没有直接回答我的问题,但它确实给了我其他的尝试。
-
titleVariable的值在您的尝试中是否发生了变化,或者是否已修复? -
titleVariable 的值是固定的,但我需要在将其显示到 h1 之前对其进行解析和编辑,我尝试使用 ngAfterViewChecked() 生命周期,但它运行了多次。
标签: angular angular8 web-component