【发布时间】:2021-03-25 13:09:02
【问题描述】:
https://angular.io/guide/elements
在询问之前,我尝试自己寻找解决方案,但我无法解决我的问题。
我有一个 Web 组件(例如 <test-component></test-component>)
对于初始化,我需要将一些参数传递给它(例如some-string-url)。
当我尝试这样做时,<test-component some-string-url="https://example.com"></test-component> 一切正常,但是对于每个网站或应用程序,该参数应该是动态的,所以当我尝试这样做时:
<test-component [some-string-url]="someVariable"></test-component> 或
<test-component some-string-url="{{ someVariable }}"></test-component> 它不起作用。我发现它的唯一方法是创建组件并将其附加到 div 中:
const widget = document.createElement('test-component');
widget.setAttribute('some-string-url', this.exampleUrl);
document.getElementById('widget-container').append(widget);
但是我可以使用另一种方式来传递参数吗?
附: ngOnChanges() 没有看到任何变化,根本没有触发。
更新:___________________________________________
我需要从我的 Web 组件 (https://angular.io/guide/elements) 中的变量中获取 @Input 属性,例如 <test-component [some-string-url]="someVariable"></test-component> 应该让我在我的 Web 组件中获得 some-string-url。
目前,当我尝试在 onInit 中获取 some-string-url 时,我得到了 undefined,经过检查后。
类似的问题,但没有解决方案Angular Elements: @Input decorator not working with variables
【问题讨论】:
-
分享
test-component的来源。 -
it doesn't work你能指定吗?你期待什么/发生了什么?你写的应该有效。当您尝试“过早”使用此变量时,通常会出现问题,然后将其传递给组件。请出示代码。 -
能否分享一下你的web组件的代码。
-
对于使用
@Input设置的值,我建议使用setter 形式,因为您不知道何时该值被填充并且ngOnInit为时过早。最安全的是这样做:@Input set someStringUrl(value: string) { [...] }。此外,每次更改值时都会调用 setter,这有时很有用