The UserForm's Render Method - ldco2016/microurb_web_framework GitHub Wiki
export class UserForm {
parent: Element;
template(): string {
return `<div>
<h1>User Form</h1>
<input />
</div>`;
}
}So I have a template() and a property called parent which I have not initialized yet, but I will. Next up I will add the render() method like so:
export class UserForm {
parent: Element;
template(): string {
return `<div>
<h1>User Form</h1>
<input />
</div>`;
}
render(): void {}
}It's not going to take any arguments and it's not going to return anything. The goal of render() is to take my template() and append it to a parent. Right now my template() is a plain string that is going to return some HTML. Well this is not technically HTML yet, I have to take the string and turn it into HTML. To do so, I had to use a template element which is a type of HTML element.
Template elements can be used for this, which is to turn some string into actual HTML that can be injected into the DOM like so:
export class UserForm {
parent: Element;
template(): string {
return `<div>
<h1>User Form</h1>
<input />
</div>`;
}
render(): void {
const templateElement = document.createElement("template");
}
}Then I am going to stick some innerHTML inside this templateElement like so:
export class UserForm {
parent: Element;
template(): string {
return `<div>
<h1>User Form</h1>
<input />
</div>`;
}
render(): void {
const templateElement = document.createElement("template");
templateElement.innerHTML = this.template();
}
}So this is the step where I take the string and turn it into actual HTML from this templateElement. Now I can take that HTML and stick it in as a child to the parent: Element like so:
export class UserForm {
parent: Element;
template(): string {
return `<div>
<h1>User Form</h1>
<input />
</div>`;
}
render(): void {
const templateElement = document.createElement("template");
templateElement.innerHTML = this.template();
this.parent.append(templateElement.content);
}
}The .content is the actual HTML that I have stuck into the templateElement. So I will take all that and append it to the parent and thats it.
Now I have to initialize the parent property. So when I create an instance of UserForm I am going to pass it the parent property and tell this class where to insert its HTML. So rather than defining parent as a property I will define it as a constructor() to define it and initialize it at the same time like so:
export class UserForm {
constructor(public parent: Element) {}
template(): string {
return `<div>
<h1>User Form</h1>
<input />
</div>`;
}
render(): void {
const templateElement = document.createElement("template");
templateElement.innerHTML = this.template();
this.parent.append(templateElement.content);
}
}