[英]Setting a property of external HTML element to a component property value in Angular?
I am trying to use an external HTML element inside the HTML of a component in my Angular app.我正在尝试在我的 Angular 应用程序的组件的 HTML 内部使用外部 HTML 元素。
So I import the external library by adding the following snippet to my index.html
file:因此,我通过将以下代码片段添加到我的
index.html
文件来导入外部库:
<script src="https://embed.xxx.co/bundle.js"></script>
In my app.component.html
file, I use the HTML element like this:在我的
app.component.html
文件中,我使用 HTML 元素,如下所示:
<dashboard welcome-message="hello"></dashboard>
This works successfully!这成功了!
However, when I now want to pass a variable to the external HTML, I define the property in my Angular component app.component.ts
file like this:但是,当我现在想将一个变量传递给外部 HTML 时,我在我的 Angular 组件
app.component.ts
文件中定义属性如下:
message: string;
ngOnInit() {
this.message = "Hello";
}
And then in the app.component.html
file, I pass the component property to the HTML like this (as described here - https://angular.io/guide/property-binding ):然后在
app.component.html
文件中,我像这样将组件属性传递给 HTML(如此处所述 - https://angular.io/guide/property-binding ):
<dashboard [welcome-message]="message"></dashboard>
The problem is that this does not work.问题是这不起作用。 The
welcome-message
property is not binding properly, and when I inspect the <dashboard>
element in the UI, the welcome-message
property is missing. welcome-message
属性未正确绑定,当我检查 UI 中的<dashboard>
元素时, welcome-message
属性丢失。
It's really weird, as for example when using the <img>
element, binding to the img src
property works fine using the approach above.这真的很奇怪,例如当使用
<img>
元素时,使用上述方法绑定到 img src
属性工作正常。
I am using Angular v13.我正在使用 Angular v13。
Any ideas on what is going on here or what the problem is?关于这里发生的事情或问题是什么的任何想法?
I have looked up everything online and I can't find an answer!我在网上查了所有的东西,我找不到答案!
I don't know about your dashboard
.我不知道你的
dashboard
。 If it's not an Angular component really I don't not if can work get the element in javascript and give value如果它真的不是 Angular 组件,我不知道是否可以获取 javascript 中的元素并赋予价值
ngOnInit() {
this.message = "Hello";
const dashboard=document.getElementsByTag("dashboard")
if (dashboard && dashboard.length)
{
dashboard[0]['welcome-message']=this.message
//or, if not work
dashboard[0].setAttribute('welcome-message',this.message)
}
else
console.log("I coudn't find the dashboard")
}
NOTE: See that each change in "this.message" you should make the same.注意:看到“this.message”中的每个更改都应该相同。 You can use a getter private _message;
您可以使用 getter private _message;
set message(value) {
this._message = value;
const dashboard = document.getElementsByTagName("dashboard");
if (dashboard && dashboard.length) {
dashboard[0].setAttribute('welcome-message', value);
//or, if not work
dashboard[0].setAttribute('welcome-message', this._message);
} else {
console.log("I coudn't find the dashboard");
}
}
get message() {
return this._message;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.