我正在尝试在 AngularComponent 中使用 WebComponent 。此 WebComponent 需要在几个 AngularComponent 内部动态呈现。因此,为了避免在所有AngularComponents中导入此WebComponent的开销,我尝试在app.component.ts
中导入此组件。我正在使用 Angular 7.2.9 进行开发。
所以我的 app.component.ts 看起来像这样。
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor() {
this.loadScript();
}
async loadScript() {
return new Promise((res, rej) => {
const scriptEl = document.createElement('script');
scriptEl.setAttribute('src', 'URL_OF_WEBCOMPONENT');
scriptEl.onload = () => {
res();
};
document.body.appendChild(scriptEl);
})
}
}
要在其中重复使用的其他* .component.html。
<web-component></web-component>
我也尝试过使用 app.component.ts 这样的
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
constructor() {}
ngOnInit() {
const scriptEl = document.createElement('script');
scriptEl.setAttribute('src', 'URL_OF_WEBCOMPONENT');
document.body.appendChild(scriptEl);
}
}
已经说过,我没有收到任何错误消息。只是未呈现WebComponent。