Last active
June 29, 2019 23:18
-
-
Save ahkohd/2919c1463b49f08f473d2513c2d097da to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { | |
Component, | |
ViewContainerRef, | |
AfterViewInit, | |
Renderer2 | |
} from '@angular/core'; | |
@Component({ | |
selector: 'ngx-pipeform', | |
template: `<ng-content></ng-content>`, | |
}) | |
export class PipeformComponent implements AfterViewInit { | |
constructor(private viewRef: ViewContainerRef, private rd: Renderer2) {} | |
ngAfterViewInit(): void { | |
// after view init, lets get things done.. | |
// filter node type of text.. | |
// if text matches pipeform syntax, replace it with the input tag | |
// the create the element and inject it into the dom with Renderer2. | |
// lets travel through the DOM.. | |
this.recurseDomChildren(this.viewRef.element.nativeElement); | |
} | |
recurseDomChildren(start) { | |
let nodes; | |
if (start.childNodes) { | |
nodes = start.childNodes; | |
this.loopNodeChildren(nodes); | |
} | |
} | |
loopNodeChildren(nodes) { | |
let node; | |
for (let i = 0; i < nodes.length; i++) { | |
node = nodes[i]; | |
// try to parse each node.. | |
this.pipeFormParse(node); | |
if (node.childNodes) { | |
this.recurseDomChildren(node); | |
} | |
} | |
} | |
pipeFormParse(node) { | |
// if the content of this node is a text node | |
if (node.nodeType === 3) { | |
// get its text content | |
const textContent = node.textContent; | |
// match the occurence of the pipe-form syntax, if found return an array of the result. | |
const pipeForms = textContent.match(/\[\[(.*?)]]/gi); | |
if (pipeForms) { | |
// strip the double square brackets from all of the results. | |
const readyElements = pipeForms.map(item => item.split('[[')[1].split(']]')[0]); | |
// create a div container with Renderer2 | |
let elem = this.rd.createElement('div'); | |
// insert the prepaired input tag into the div. | |
elem.innerHTML = readyElements.join(' '); | |
// replace this current node with the new div node we just created. | |
node.parentElement.replaceChild(elem, node); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment