Background
I am trying to create a blog using Angular (5). I am using markdown and storing that data outside the application. It downloads the markdown, parses it into an html string, then binds to the innerHTML of a div.
I understand that I am working against the grain, but I would really like to be able to create an elegant solution here.
Problem
Having the ability to use custom components gives us the ability to do a bunch of stuff with our blog that we won't be able to do otherwise. Signup components, custom widgets, etc. We can do all this and still have the ability to store the content separately outside of the application.
Custom components are not detected from the innerHTML string. Which doesn't allow it. It seems like DynamicComponentLoader used to provide a solution for this, but not anymore.
Clarity
I am not trying to render only the html, or only a single component. I want to render the html and all components included.
I also don't care that it's bound to the innerHTML property, it just seemed to get me the furthest. I can/will use a resolver if that would help.
Example
https://stackblitz.com/edit/angular-wylp55
As you can see the hello component renders in the html, but not the component itself.
Any help would be appreciated.
So I finally figured this out and did a write up.
Here's the link to the updated stack blitz.
https://stackblitz.com/edit/angular-dynamic-html.
I also did a full write up on my company blog. https://www.arka.com/blog/dynamically-generate-angular-components-from-external-html.
Related
i am creating a e-commerce website using html/css. what i am trying to achieve is that i need same template for all product pages after clicking on the product. And i want to do this without actually coding every page using html and css. is there anyway to do this?
i tried to code all pages but that will be impossible to finsh if i keep on doing it, i want an effective way of doing this.
You can use plain JS to achieve the same or can use JS libraries like React JS, Angular JS, etc. for versatility. But all of these would require a good knowledge of coding.
And, to skip coding, I'll suggest you use WordPress + WooCommerce, all the required features are free and you don't have to code a single line, it's all GUI.
You need to add Javascript for this. The easy thing will be to work with a Javascript library called React.
In react you will make a component called a product card! and now you can pass your data to the product card by mapping the product list. You don't need to write product data showing HTML CSS for every product. Just write it one time and use it as many times as you want with React.
Here is the official React documentation
As example, I dynamically create instance of some custom HTML element.
After this, I twice use document.body.appendChild() and this work, but this should no be. What I may do for prevent this?
I put sample about this situation below in the text. RandomParagraphSizePlaceholder is simple web-component from some book. I use it only for illustration purposes.
https://jsfiddle.net/h6cxjae5/
P.S. I see, that is something wrong with web component, may be.
Only one instance of web component exists in web-page.
But web component content is duplicated. May be, because it created in connectedCallback. I dont very famimiliar with web component :(.
You get two instances, because your code:
this.appendChild(document.importNode(placeholder.content, true));
effectively makes a copy (importNode) and then appends another element.
connectedCallback (corretcly running twice) has (in this case) nothing to do with it.
https://developer.mozilla.org/en-US/docs/Web/API/Document/importNode
I am trying to support the same type of thing as React.Children
My code looks like
const elem = document.getElementById("profile")
const render = hyperHTML.bind(elem);
const name = elem.textContent
render`<b>Hi ${name}</b>`
So the API looks like
<div id="profile">alax</div> 🢂 <div id="profile"><b>Hi alax</b></div>
and I am using MutationObserver to rerender on content change
But if the content is changed. hyperHTML says its rending to the right element.. but the element keeps its innerHtml(No update)
I can see the <!--_hyper: -2001947635;--> is removed then the content is set but setting up the render & hyperHTML.bind again does nothing
Any thoughts would be great! Thx
Update
The fix to the above problem is to call hyperHTML.bind`` then your normal render using hyperHTML will work
Context -
I am using hyperHTML to create a custom element library(hyper-element)
My use case: I work in a mix-tech project (some people use jQuery)
Side note, on the why. I want to support something like partial templates
Example of a partial template:
<user-list data="[{name:'ann',url:''},{name:'bob',url:''}]">
<div>{#name}</div>
</user-list>
Output:
<user-list data="[{name:'ann',url:''},{name:'bob',url:''}]">
<div>ann</div>
<div>bob</div>
</user-list>
This is one use of setting custom content in an element you control
At the moment I have the setting of the content by 3-party working/re-rending
https://jsfiddle.net/k25e6ufv/16/
My problem is now: it is rending another custom element and getting the pass content to child element
It looks like hyperHTML is setting the child element's content in front to the element and creating the element without setting the content
Scroll down to bottom of source to see implementation!
https://jsfiddle.net/k25e6ufv/14/
Rending crazy-cats:
Html`
xxx: ${this.wrapedContent} zzzz
`
Current output:
wrapedContent: ppp time:11:35:48 ~ crazy-cats: **Party 11:35:48** xxx: zzzz
<crazy-cats>Party 11:37:21 xxx: <!--_hyper: -362006176;--> zzzz </crazy-cats>
Desired output:
wrapedContent: ppp time:11:35:48 ~ crazy-cats: xxx: **Party 11:35:48** zzzz
<crazy-cats> xxx: Party 11:37:21 zzzz </crazy-cats>
I will try to answer as best as I can, but I'll start saying that when asking for help, it'd be much easier/better to show the simplest use case you are trying to solve.
There is a lot of "surrounding" code in your fiddles so that I'll try to answer only to hyperHTML related bits.
hyper-element ?
I am not sure what's the goal of the library but hyperHTML exposes hyper.Component, and there's also an official HyperHTMLElement class to extend, which does most of the things you manually implement in your examples.
I'll keep answering your questions but please consider trying, at least, the official alternative and maybe push some change there if needed.
partial templates
hyperHTML pattern and strength is the Template Literal standard. Accordingly, to generate TL from the DOM would require either parsing of the content or code evaluation. Both solutions aren't the way to go.
Custom Elements require JavaScript to work, and without JS your partial template is useless and also potentially confusing for the user/consumer.
You don't want to define what to do with the data in the layout, you want to define a Custom Element behavior within the class that defines it.
That means: get rid of old-style in-DOM output, and simply use the Custom Element class to define its content. You maintain the related class only instead of maintaining a layout that has no knowledge about how the CE should represent that data.
TL;DR the following is a bad hyperHTML pattern:
<user-list data="[{name:'ann',url:''},{name:'bob',url:''}]">
<div>{#name}</div>
</user-list>
all you want to do is to write this:
<user-list data="[{name:'ann',url:''},{name:'bob',url:''}]"></user-list>
but be careful, the data attribute in hyperHTML is special only if passed through the template literal. If you want to pass JSON to the component, call the attribute differently.
// hyperHTML data is special, no need to use JSON
render`<c-e data=${{as: 'it is'}}></c-e>`
Above snippet is different from having JSON as data attribute text so your example should use data-json name, and the class should remember to JSON.parse(this.dataset.json) in its constructor (or have an attribute observer that does that for you)
hyperHTML owns elements
When you write:
it looks like hyperHTML is setting the child element's content in front to the element and creating the element without setting the content
you are assuming you should care at all what hyperHTML does: you shouldn't.
The only thing you should understand is that hyperHTML owns the node it handles. If you trash those nodes via different libraries or manually, you are doing something wrong.
hyperHTML(document.body)`<p>hello ${'world'}</p>`;
// obtrusive libraries ... later on ...
document.body.textContent = 'bye bye';
// hyperHTML still owns the body content
hyperHTML(document.body)`<p>hello ${'world'}</p>`;
Above snippet is perfectly fine and totally wrong at the same time.
You don't update the body content manually, you don't interfere with its content via jQuery or other libraries, and you should never trash the content at all.
Once you chose hyperHTML to handle a bound context, that's it, you've made your choice.
This is true for pretty much every library on this world. If you use Angular to create something and you mess it all via jQuery, that breaks. If you write backbone templates and you mess later on with their content manually, that breaks.
If you bind an element to hyperHTML and you mess it up with other libraries, that breaks.
The only thing that won't break are wires, meaning the moment you create a wire, you can append it directly and that's actually a DOM node so it will be there, and it will be handled by hyperHTML.
Yet you should use hyperHTML to handle those changes, never jQuery or JS itself.
The output is right
When you say that the output should not contain the comment you are assuming you should care what output is produced via hyperHTML: you shouldn't!
hyperHTML uses comments as delimiters and these are absolutely fine for both performance, being unaffected by repaint and reflows, and for partial changes like the following one:
hyperHTML(document.body)`<p>${'a'} b ${'c'}</p>`
Both a and c will have a comment as anchor node to be able to update their content with anything later on.
hyperHTML(document.body)`<p>${[list, of, nodes]} b ${otherThing}</p>`
You change interpolations? All good, hyperHTML knows what to replace and where.
force-own the content
If you use a different template literal to re-populate a bound node you are trashing the cache and creating new content.
At that point you are better off with innerHTML because all the features of hyperHTML will be gone.
To start with, if your content can change so much, use an array.
hyper(document.body)`${['text']}`;
// you can clean up the text through empty array
hyper(document.body)`${[]}`;
// re-populate it with new content
hyper(document.body)`${['a', 'b', 'c']}`;
Above example is still better than changing template because all the optimizations for the content will be already there.
However, if you want to be sure the node the initial one created via hyperHTML, assuming no third parts script mutate/trash that node, you can use a wire.
const body = hyper()`<p>my ${'content'}</p>`;
document.body.textContent = '';
document.body.appendChild(body);
It's a bit extreme but at least faster.
As Summary
It looks like you are trying to sneak in hyperHTML into an application that trashes layout all the time through different third parts libraries.
Unless you create a closed Shadow DOM reference and you drop partial template through layout, you'll always have issues with libraries based on side effects with DOM content, libraries that mutates elements they don't own.
In hyperHTML the ownership concept is key, like in React you cannot change at runtime the defined JSX for the component, you should never try to change at runtime the defined template literal for hyperHTML.
Now, as much as I'd like to solve all your issues, I feel like it's right to ask you: are you sure hyperHTML is really the solution for your current app? It looks like surrounding side-effects caused by third parts libraries would constantly break your expectations if you don't use closed mode Shadow DOM and hyperHTML only to update your DOM.
I'm trying to put together a library of custom AngularJS directives that show the live functioning component and underneath it the code snippet used to make that component. I want the example and snippet to be generated from one shared html pattern.
I tried building a directive that copies the content of the div from the example as a string, but by the time that directive runs the component directives have already digested and made alterations to the DOM, making it a bad representation of how to build that component.
I don't want to use a codepen type solution, since I want everything to be under my server and my control, but I'm drawing a blank on how to show example snippets pre-AngularJS alteration. There's no need to be able to have a live code editor, just something to copy snippets out of.
I wan't to add some interactions to my Angular 2 project to enhance its user experience. I know how to interact with DOM, or change the status of element property. It is possible to write code for each of my component. But there are some examples which will be used site wide, for which I don't want to repeat the code everywhere I want to use it.
A simple example will the fade in when scroll elements. I know how to achieve this in a particular controller, but I need help to make this behaviour global without code repetition.
I Javascript / jQuery, we can have a master js file included which will have the event listeners bound to the elements, which is available for all pages. How to achieve similar in Angular?
This can mostly be done with Directives. Taking your example, you would create a [scroll-fade] Directive:
#Directive({
selector: '[scroll-fade]'
})
export class ScrollFade {
}
You'd then need to listen for the global scroll event, with #HostListener('window:scroll') and apply your styles to the :host element.
You would then use it by applying it to the elements you want affected:
<div class="scroller" scroll-fade></div>
If you need something more complex, you could always build a Shared Module where you would create reusable components, without repeating the code - which you could then transform into a library and share back with the community.
Theres an answer here on StackOverflow that explains how to.