问题描述
https://angular.io/guide/elements
在询问之前,我尝试自己找到解决方案,但我无法解决我的问题。
我有一个网络组件(例如 <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() 没有看到任何变化,也根本没有触发。
更新:__________________________________________
我需要从我的网络组件内的变量(https://angular.io/guide/elements)中获取@Input 属性,例如 <test-component [some-string-url]="someVariable"></test-component>
应该让我在我的网络组件内获得 some-string-url
。
目前,当我尝试在 onInit 中获取 undefined
时,我得到了 some-string-url
,afterviewchecked。
类似的问题但没有解决方案Angular Elements: @Input decorator not working with variables
解决方法
我不确定为什么它对您不起作用,这两种绑定格式都应该起作用。
这是一个working example:
test.component.ts
export class TestComponent {
@Input() someStringUrl: string;
}
app.component.html
<test-component [someStringUrl]="someVariable"></test-component>
<button (click)="increaseCounter()">Increase Counter</button>
app.component.ts
export class AppComponent {
private counter = 1;
get someVariable() {
return `http://www.fake-address.com/${this.counter}`;
}
increaseCounter() {
this.counter++;
}
}