在使用 Angular 元素时,查询参数可能会一直为空。解决方法是使用 Renderer2 类的 createText 方法创建带有查询参数的 URL,然后将其添加到属性中。
示例代码:
import { Component, Renderer2, ElementRef, Injector } from '@angular/core';
import { createCustomElement } from '@angular/elements';
@Component({
selector: 'app-query-params',
template: `
Query Params: {{ queryParams }}
`,
})
export class QueryParamsComponent {
queryParams: string;
constructor(
private renderer: Renderer2,
private elementRef: ElementRef,
private injector: Injector,
) {
const queryParams = new URLSearchParams(window.location.search);
// Create URL with query params using Renderer2
const href = this.renderer.createText(
`/my-element?${queryParams.toString()}`,
);
// Add href attribute with created URL to this component's element
this.renderer.setAttribute(
this.elementRef.nativeElement,
'href',
href.textContent,
);
// Get query params from window location
this.queryParams = queryParams.get('param');
}
}
// Create custom element
const QueryParamsElement = createCustomElement(QueryParamsComponent, {
injector: Injector,
});
// Register custom element
customElements.define('my-element', QueryParamsElement);
注意:在使用 Renderer2 时,需要将其注入到组件中。而 createCustomElement 方法必须传递 Injector 对象以进行注入。