Я пытаюсь добавить префикс к вводу номера телефона после загрузки компонента, но получаю сообщение об ошибке. В обычном веб-компоненте метода linkedCallback() было бы достаточно, но здесь он, похоже, не работает. Как я могу это исправить?
Ошибка, которую я получаю: Uncaught TypeError: невозможно прочитать свойства null (чтение «getAttribute»)
import { LitElement, html } from "https://cdn.jsdelivr.net/gh/lit/dist@3/core/lit-core.min.js";
import "https://unpkg.com/[email protected]/build/js/intlTelInput.min.js";
import { formattedArray } from "./countries.js";
export class Form extends LitElement {
static properties = {
name: {},
modalContent: {},
};
constructor() {
super();
this.countries = formattedArray;
}
render() {
return html`
<form class = "flex flex-col gap-3" @submit=${this.handleSubmit}>
<input type = "text" class = "form-control" placeholder = "First name" name = "first_name" />
<input type = "text" class = "form-control" placeholder = "Last name" name = "last_name" />
<input type = "text" class = "form-control" placeholder = "Address" name = "address" />
<input type = "text" class = "form-control" placeholder = "Zip Code" name = "zip" />
<input type = "text" class = "form-control" placeholder = "City" name = "city" />
<select class = "form-control" name = "country">
${this.countries.map(country => html`<option value = "${country}">${country}</option>`)}
</select>
<input type = "tel" class = "form-control" placeholder = "Phone" name = "phone" id = "phone" />
<input type = "email" class = "form-control" placeholder = "Email" name = "email" />
<button type = "submit" class = "btn btn-primary">
Continue
</button>
</form>
`;
}
connectedCallback() {
super.connectedCallback();
// Initialize intlTelInput
const input = document.querySelector("#phone");
window.intlTelInput(input, {
initialCountry: "auto",
separateDialCode: true,
utilsScript: "https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.8/js/utils.js", // Add the correct path to utils.js
});
}
handleSubmit(event) {
event.preventDefault();
const formData = new FormData(event.target);
const formObject = Object.fromEntries(formData.entries());
// Do something with the form data, for example, log it
console.info("Form data:", formObject);
this.dispatchEvent(new Event('submitted', {bubbles: true, composed: true}));
}
createRenderRoot() {
return this;
}
}
customElements.define("custom-form", Form);
Как упоминалось в документе lit Используйте firstUpdated
для выполнения разовой работы после создания шаблона элемента.
firstUpdated() {
// Initialize intlTelInput
const input = document.querySelector("#phone");
window.intlTelInput(input, {
initialCountry: "auto",
separateDialCode: true,
utilsScript: "https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.8/js/utils.js", // Add the correct path to utils.js
});
}
Рабочий пример