248 points · by theodorejb · 6y ago · 299 comments
This was a fast release cycle. It was back in November 2019 we were talking about 3.7, and now it's in.
I'm not even thinking about Ivy. But it's nice to have all the nice comforts of typescript ready and working out of the box. (I mainly work in React, but dabble with angular/vue to stay up to date)
And what a smooth update process (abbreviated):
ng update @angular/cli @angular/core
** Executing migrations of package '@angular/cli' **
** Executing migrations of package '@angular/core' **
Your project has been updated to Angular version 9!
For more info, please see: https://v9.angular.io/guide/updating-to-version-9My app is a big stack of workaround stuff that might break anytime. Because that is how angular work. Some stuff work in a context and doesn't in an other. Nobody's know why ! They have so much issue on Github that they need a bot to close them after a while. They hope the bug disappear by himself ?
I've been working with Angular2+ for 3 years and I haven't met any bug.
Know the concepts, apply them and you'll have an easy trip.
Give me a break, this isn't true for any code in existence.
There is software that's incredibly solid.
I have personally witnessed companies take guys who have been slapping together "apps" in jQuery / .NET for the past 10 years and tell them "it's time to make the stack modern" and "we're going with Angular because we're a Microsoft house".
Things go very bad very quickly.
If you don't take the time to understand the Architecture behind scalable modern web applications you're going to have a bad time.
Anyone can slap together a quick and dirty app with Angular or React - not everyone can scale one correctly with thought given to the architecture behind these applications.
Is ms invested in Angular?
It's a Google project, isn't it? Is it first-party in dot.net? I though that was Blazor?
I don't think Angular is a bad choice across the board, but you need to weigh this heavily when deciding to use it.
Neither of those is Angular-specific. In fact, of those you mentioned jQuery is the library with the unusual, idiosyncratic concepts.
Yet I agree, a lot of things in my project is wrong and maybe blaming the framework for the mess is too easy. But I really do not enjoy working with Angular. Also, learning to use RxJS was a painful experience full of frustration.
I have a backendService that use the httpClient; it's a wrapper that automate stuff to make API request. I guess it's pretty common. I have a provider for APP_INITIALIZER. It can use the HttpClient but not the backendService. The backendService work everywhere else of course.
Join us, you’ll enjoy the ride!
Based on personal usage of React, it's no easier than angular or any JS based framework like Vue (which in my view more sensible than react). You add state management, templates, router and 1000's of npm packages to do anything simple and react soon becomes an unmaintainable nightmare with emany vulnerabilities if you do not upgrade. An app is not just simple react but many of the npm packages (although it's true in general for JavaScript eco-system which is by default is insecure and maintenance nightmare unless there is an extra amount of work done to secure it).
Angular at least provide a decent complete single framework to work with and a unified documentation, there are issues with it, but react is same when you need any reasonable size app from it.
React gives you an easy start with false sense that it's easy, than becomes just too convoluted and complicated with the addition of different components as soon as app starts growing. Maintaining and upgrading apps based on react is very difficult as one version to another it introduces breaking changes. Angular had similar thing from angularjs to angular 2, but slowly they made it much better but letting compiler do more work.
Ivy tree shaking compiler will give a fight to upcoming compiler framework like svelte and keep the size smaller and may be in some cases much smaller than react app bundles, will wait for the benchmarks and size comparisons.
I am still waiting for a simpler way of developing web apps, elm looked very nice, but it is still far from ready for use in the same way as Angular or react yet.
It feels cleaner and more solid.
You don't actually have to do that. React just turns your data into DOM elements, most of the time it's a simple transformation.
Otherwise, how you architect your application is up to you. You don't need to overcomplicate things by following the latest trends, you don't need a ton of dependencies to do simple things. You don't need templates at all.
Angular is complicated by default. It makes design decisions for you that you probably wouldn't have made, and then sometimes it reverts those decisions, making you clean up the mess. React code very rarely breaks.
> Ivy tree shaking compiler will give a fight to upcoming compiler framework like svelte and keep the size smaller and may be in some cases much smaller than react app bundles, will wait for the benchmarks and size comparisons.
Angular bundles are huge by default, it has a long way to go. Tree shaking already works with React, you just need to set your build up that way. Also, don't assume that a compiler will make your build smaller, it may well inline a lot of stuff and end up larger.
So no, I didn't enjoy the ride, at all.
Well-managed react is incomparable in power. Try to make a library like react-three-fiber using Angular, in less than 500lines of code.
An Angular 2+ app built in 2016 (when Angular 2 came out) wouldn't build anymore.
An Angular 1 app didn't even need a build step, so that would probably still work fine.
Unless it's doing unsafe or nonstandard stuff in the first place, like idk, cross-domain requests or weird stuff with iframes or whatever it was Google tried to do when it added an extension that tried to do preloading and stuff like that.
Did you try to actually upgrade the react version? Lots and lots of breaking changes in that time, some really major ones along the way. Especially when upgrading react also forced one to change router etc.
By all means, upvote criticism that is properly argued and backed up with evidence. But upvoting these kinds of comments is the equivalent of posting anti-vaccination memes on Facebook.
What I don't like is the verbosity and boilerplate... here's 2 examples:
- Routing boilerplate is convoluted and time consuming. I think Nuxt.js has a much nicer implementation of SPA routing, where the filesystem is used to map the routes.
- Angular modules are verbose, redundant and don't even truely encapsulate dependencies anyway. You can easily create implicit dependencies by relying on services instantiated in higher level modules.... which is bad
I love using Typescript though!
From what I understand of React, you need to pick and chose the libraries (and versions of those libraries!) to use for your app, and then keep the versions of all the different libraries up-to-date and in sync with each other. Sounds like a maintenance nightmare.
The other reason is the first class TypeScript and RxJS support.
I've seen people tout this as a benefit for certain ecosystems for years and years and years, and I think it's a big bag of crap. Maybe if you are ultra talented and ultra disciplined, it's possible to stay on the ball and make things work when you are gluing together disparate pieces and shaving an untold herd of yaks.
But for mere mortals, having sensible defaults and pieces that were designed and built together is wildly more productive.
I was more amenable to the libraries-not-frameworks argument a decade or two ago, when release cycles were once or twice a year, libraries were mostly independent, and granularity was much coarser. Now it's just too goddamn much work to keep things sane. I do not have time to dedicate a day a week to troubleshooting why updating package X has pulled a new dependency on library Y, which is incompatible with library Z.
Not really, since by design React doesn't care. You can use a years-old version of React Router without any problems.
It reminds me of a great hack where game developers used to hide a large memory allocation early in the game development process and when they ran into memory constraints towards launch they'd just comment out the line and instantly save the day. Artificially constraining the memory caused intermediate development to be more frugal and ultimately allowed them to get where they needed to be by the end of it.
We also worked on making the runtime tree-shakable, so in your final bundle you can get only what you use.
Additionally, we made sure the code we generate compresses well with popular algorithms.
Is that minified and gzipped?
That being said, 973kb seems like large-sized rather than mid-sized to me.
https://krausest.github.io/js-framework-benchmark/current.ht...
I know micro benchmarks don't tell the whole story, but when you consistently wind up on the slow end it's not a good look.
Edit typo
Having used both Angular (since 1.0) and React (only recently), it's obvious why React is more popular. Any decent engineer can be productive in React within a day since the concepts are so intuitive and simple. With Angular, if you don't really know how things work, you are going to struggle a lot for a while.
While i can't speak for the rendering performance, the design itself is definitely elegant and not built for "code monkeys" but real engineering productivity
I think that just by using Hooks and Contexts you can get a lot done in a predictable way without adding too much complexity. With typescript and a proper IDE you get also wonderful type-checking and refactoring capabilities.
I used AngularJs (1.x) a lot before and in comparison it was both more complex and full of unexpected behaviors.
I have less experience with Angular (2+), but I found it much more complex and in some parts over engineered.
What do you even mean?
Redux was a simple and elegant implementation of the unidirectional data flow (aka the Flux pattern). It came out during the time when the state of the art was Angular 1.x (aka AngularJS)'s two-way data binding, requiring a lot of dirty checking. Redux might or might not (the story is moot) have been influenced by Elm, which has exactly the same concept of actions, state modifications in response to actions, and re-renders in response to state modifications; all as pure functions; and Elm developers are finding this approach enjoyable and predictable. But even Elm aside, the pattern that redux is using, i.e. communicating via messages (actions) and subscribing to state changes in connected components, is a variation on the age-old, battle-tested event sourcing and pub/sub. What's so bad about that?
Is it just the pairing of React / Redux you find unappealing?
Your feedback is disappointingly vague but you seem passionate about it so I assume there’s something deeper here.
react has always been approx where it is now. but there are a lot more faster libs in the table.
Didn't know that. What I thought I knew is based on years of breathless claims about React's great performance. This is eye opening. Even Angular 8 does better in these benchmarks.
that metric is slower in general because libs with simple reconciliation strategies will tend to do work for every row between the two swapped ones (2,998).
Pretty cool.
Angular was built specifically around avoiding an entirely different problem that the heavily debated issue here of overengineering: Multiple teams that build out complicated and feature laden systems in parallel need to make concessions to allow interoperability.
If your organization is culturally flat, Angular prevents the core of your application from diverging in unmaintainable ways.
Regardless of the underlying philosophies, the choice between React, Vue and Angular is a very real one businesses have to make everyday, so it makes sense to compare them.
Also it's worth nothing that React and Vue scale. They work as well for small, scrappy projects as they do for large enterprise ones. I wouldn't say the same for Angular.
Supporting a large 1.x codebase right now, and would love to start incrementally moving to angular.
I maintain a sizable 1.x codebase and am deciding what to move to, since 1.x is dead next year. I just don’t see a good reason to go to 2+. It’s a different framework. All of the UI libraries we built upon (ng-grid, angular-ui) are either gone or different enough that we will have to redo all of our code no matter what. If I have to switch frameworks anyway, I want to go with something simpler (no custom module nonsense, no annotations, no hierarchical dependency injectors, hell, no classes!) with a healthy ecosystem.
React with hooks, bootstrapped with CRA, is the clear winner for me. It’s just so much more straightforward to reason about, and way faster to build things with too. I made a toy app in Angular a year ago to check it out, and had a hell of a time even getting the simple data model working right. With React, day two had me already wiring up a dashboard with charted details that responded to a calendar widget I had customized to show QoS at a glance. I was looking at Vue too before I read up on react hooks, but once I saw functional components everywhere I was...erm...hooked. Sorry.
Now if only I can convince them to let me use ClojureScript...
Having used React for some years now, I have to say: I wouldn't compare the two. React's atomic ecosystem is perfect if your stack of tools you embed doesn't grow too large.
However as soon as you want the feature set Angular provides out of the box IMHO you're screwed.
Except maybe for modelling/simulating concrete classes of objects (ie, as in Simula, the language).
Proper multiple dispatch (a la common lisp CLOS) seems rare - I'm guessing java/c++ seemed like a sane trade-off for some type safety - but they probably should've stuck to self/smalltalk (for Java) or looked to standard ml/common lisp (c++).
I still don't understand why Javascript got classes, rather than some paint on the prototype system.
The more I can compose with pure functions that operate on immutable data, the happier I am.
We’ve had a bunch of long-standing state management bugs and performance issues too ($watches, $watches everywhere, nor any prop’s in sync) that we built a lot of cruft around trying to fix, mostly due to two-way binding and our weird use case. Some were unfixable due to the framework and others due to bad early decisions. But This Time!!
It will definitely be fun to rewrite. The app is so much like a web-based dumb terminal that a view-layer library like React was probably always a better fit for us, had we known about it when we started the project. Plus the JS ecosystem is a lot nicer now: arg destructuring and VS Code’s intellisense thanks to es6 imports are both big productivity wins. Also, not having to maintain a gulpfile is its own blessing.
* Determine exactly how moving to a new framework will benefit your users. If it doesn’t, why are you doing it? It is going to be a lot of hard work and your users will not care you’re on a new framework.
* evaluate if Angular really is the right choice to upgrade to * if it is, do not mix the code in one repo. Use two repos.
* Migrate route by route, starting with lowest impact pages first. When user clicks on the route served by the new angular page it will point to the new app
* to support this, you’ll need to build out foundational modules critical for the switching to happen, e.g. auth, common header, footer, menus etc
* how the switch happens between routes is up to how your app is served. You will need to configure the domain to stay the same between serving the different apps.
* update your deployment and testing strategies to account for two apps going out instead of one.
* we took a bell curve approach, lowest impact routes first, then peaked with critical routes, then back to less and less important pages. This allowed a gradual ramp up to work out the kinks but at some point you will need to get your most important stuff moved over so you’re not building two systems.
* get buy-in from stakeholders that this migration is going to add value for users. Get them excited so you are working together to get it all moved over.
* allocate x% of Dev time to the transition.
* agree on a date for each route and for the full transition so work can be prioritized.
I’m sure there’s loads of blogs with more specifics. Just wanted to share my experience at a high level.
Another thing to think about though is how you're currently doing state management. Angular 9 is all about RxJS, and if you're currently managing state without it, your migration will be that much harder.
Personally I wouldn't go for a vanilla JS application, not unless the script / application part of it are minimal.
The mental model for React is much simpler than Angular's.
In React, There are two concepts one needs to understand: Components, and Hooks. JSX too, but as a web dev the HTML-like syntax was already familiar.
In Angular, you need to understand: the binding syntax; Components; Templates; Factories; Modules and Services. And learning bindings also means learning RxJS (which I love as a standalone lib, but is a big cognitive load when coupled with the rest of ng).
Even just comparing the "Fundamentals" page of Angular versus the "Main Concepts" of React (which, isn't exactly the best measure of complexity, of course, but it's A measure), you can see Angular spends 8 of its 10 sub-sections explaining essentially-required concepts, while in React it uses 6 out of 12 sub-sections.
React is much more concise in terms of concepts, and instead just has a bunch of common patterns that are sufficiently approachable and memorable, but most importantly can be "rediscovered"/"derived" on your own, rather than relying on framework-provided "black box" concepts.
And the total load is still in my perspective smaller than Angular. I have never even casually used Vue (I've since switched to gamedev as a profession), so I cannot comment on it, but from a cursory on its docs, it seems like a leaner Angular, which is good.
We understand that we can work on simplifying the mental model of Angular. This is something we're working towards. We're careful with in process though because we want to provide a consistent, backwards compatible development experience.
Now, if angular would prove substantially better in terms of performance or maintainability or so, that might've been ok. But they're not. Performance is on par, I find refactorings actually harder because of the heaps of boilerplate angular requires, etc. They invented way too complex solutions to solve problems that either don't exist, or other frameworks solved better.
To give just one example. If you want to dynamically import components, in react you just use a dynamic import, since it's just like importing any other js function. Compare this to the angular way and draw your own conclusions: https://angular.io/guide/dynamic-component-loader . Granted, angular may have things that are easier to achieve than react as well. And I don't like the looks of jsx and so on. But my generic experience was that angular was always working against me. It reminded me of my java EE days.
Would you suggest I go with Angular or React?
It's a fairly complex project, involving user based label designs, data manipulation, etc.
I am API based server and a heavyweight front-end.
Never used it myself, but the guys from Flipboard made this react canvas renderer which might be useful for you: https://github.com/Flipboard/react-canvas
Not saying one is better than other but in my opinion, entry barrier for React is lower than Angular which may be an important factor for React's popularity.
There’s no good or bad. As in any architectural adoption, it should’ve based on your team’s capabilities and support capabilities.
Experience matters too. There are good reasons to use either platform.
No, if it's overengineered.
Enterprise Java and .NET shops usually reach out for Angular first.
And I have no intentions to ever advise React with its FP approach with a myriad of endless libraries, to devs that just want to get stuff done.
The learning curve is steep I agree. There does feel like there is a lot of ceremony and boilerplate required for even the more basic "hello world". Also if you are not familiar with RxJS before learning Angular then that is a second learning curve that you need to know too and it is a challenge.
The docs are also very frustrating:
- the API reference is usually just auto-generated with perhaps a single sentence saying "The FooBarDooDad does foo to bar" with zero other content, e.g. https://angular.io/api/core/Query
- the tutorial guides are absolutely huge epic documents, scrolling screen after screen after screen after screen and are far too long and far too convoluted to be useful in my opinion. It feels like they are several entire chapters lifted from a printed book or something, rather than something useful for a developer trying to implement something. E.g. https://angular.io/tutorial/toh-pt6 (and that is just part 6!) I've been doing this for years and I still hate having to go back to those docs.
- the tutorials are all talking about some "Heros" app that I have no idea what it is or what it is doing. I wish they just had examples for the simplest-possible case in stackblitz-widgets that does not need me to know the ins-and-outs of their sample app.
That said, once you are up and running with Angular I have found it is very easy to use, and RxJS is really nice once you get your head around it. Everything works largely as expected, and you can more or less forget about Angular and concentrate on the logic. As far as boilerplate goes, I have found that once you have done the boilerplate once, you just copy-paste from one file to another then do a search-replace for the name etc - takes perhaps 10 seconds etc before you are writing logic.
I would like the Angular team to add some sort of "official" state management feature though in the future. In my view, it is the biggest missing gap in the library and you either have to use NgRX as a separate library, or have to botch a global app state by using either a Service or a convoluted @Input/@Output chain
You are not the only one mentioning this here. Do you believe it's wise to start with learning RxJS before you even approach Angular if you are a VanillaJS/JQuery "dinosaur" looking forward to learn Angular?
https://rxjs-dev.firebaseapp.com/api
Reading the guide and pondering the following table helped me understand how other mechanisms in JavaScript work together and relate to each other, and the corner that Observable occupies:
https://rxjs-dev.firebaseapp.com/guide/observable
>Observables are lazy Push collections of multiple values. They fill the missing spot in the following table:
SINGLE MULTIPLE
Pull: Function Iterator
Push: Promise ObservableNo need to master it - probably spend an hour or two on RxJS tutorials & samples to get to know it before jumping in with Angular so you know where the join is between Angular + RxJS.
I then tried React and it just kind of made sense. Since then from the sidelines I've heard Angular has gotten much better but personally don't see any reason to use anything other than React at this point in time.
I haven't used Svelte at all but it looks very interesting.
Management was very happy with how modern the stack felt
Sales came to a halt for 2 years since features came to a halt.
Turns out Angular is freaky hard to do right.
There were definitely Angular-related issues, but they were replacing a lot of "my state machine is out of sync" issues that just scopes and watching mostly solve (except for the prototype inheritence gotcha)
I guess whether or not you'll be productive with Angular depends a lot on your experience and expectations. I come from the C++ world and Angular felt like MFC, so oddly familiar.
Popularity is not a useful metric when evaluating frameworks. Community engagement and core team motivation are, and some people may use popularity as a proxy for those measurements.
That said, I think, for bigger groups/companies working on a complex product, I can see that Angular ensures a certain level of "architecture" and code organized correctly instead of being coded to each dev's personal style.
But way too complex for single-person apps or for simple SPAs.
All that to say Angular is less popular because it is too complex to learn and use quickly.
Why use anything but Flutter if you choose Dart?
React: Write a function that generates a piece of HTML. Use standard event handlers to manage user interactions. Update state via setState methods. Ship it.
The method for passing data to a dialog component is to import a magic constant and inject a data field into it's constructor? It's a completely over-engineered, nonsensical solution for a problem that doesn't even exist in React. There's so much stuff you have to be familiar with in Angular just to build the simplest features.
I can only guess that "same team" was a design-centric subteam for Angular while the engineering-centric team worked on the framework/documentation itself, or that Angular Material was under pressure to get implemented before all the best practices were established and by then they were stuck with the API.
And every release .NET just keeps moving closer to the dumb systems. Simple and raw is good, keep the magic away
The amount of complexity is mind boggling.
I mean, look at Flask in Python. Or even Expressjs in Node, why can't Microsoft come up with a simple framework that can run well on the .NET runtime?
I am a huge fan of C#, having used it for Desktop app development.
I would love to have a framework like flask in the .NET ecosystem.
React seems a bit better, but they don't seem to support older releases at all.
First off, Angular versions post 2.0 are nothing like AngularJS/1.x -> Angular/2.0. They are much more incremental and even the two times the entire renderer has been re-written it was an incredibly gradual process over multiple major versions with seemingly few changes to component and template APIs.
Second, upgrading between Angular versions couldn't be easier thanks to angular schematics. The process takes seconds and for specific rarer exceptions the team maintains this fantastic guide here: https://update.angular.io/
The problem isn't how it's handled or how incremental it is, it's that there are so many upgrades with breaking changes, at least that's what they're communicating to me with their version numbers. There's also the lack of any real LTS versions I mentioned, 18 months doesn't cut it.
> They are much more incremental and even the two times the entire renderer has been re-written
Telling me that they've rewritten major components that frequently isn't exactly convincing me of the stability, its validates my previous belief that it isn't stable enough.
When they've got versions that are supported for 5+ years post release I'd consider it stable. It doesn't matter how good your upgrade guide is when you run into a bug or limitation with the current version and realize that you have to upgrade the entire framework and deal with all the breaking changes to get around it.
Compare that to react where you've got at least 3 years (assuming they follow semver) between breaking changes.
Does anybody here use Angular for their customer facing websites?
So far I have only deployed Angular once in production for an IoT Dashboard.
It was based on Material Dashboard, it was good enough for the monitoring use case, but it was for on-premises deployment.
It is still early days, and isn't suitable for every use-case, but it could be the answer you're looking for. Continue to write back-end code only. But with the benefits of quick-response front-end app. I'm a total convert (evangelist) who has been increasingly put off by the evolution (devolution?) of front-end development over the past 5-10 years. This could be one way of the mess.
It's the output I'm worried about. The HTML outputted by Angular pre-Ivy is verbose and runs very slow on old browsers (IE9, with polyfills). A customer facing website can be visited by anyone, from a tech savvy Linux user to your grandma which uses Internet Explorer and thinks Facebook is the internet.
I don't want to face the wrath of clients who realize that their website is slow and non-optimized because I'm using Angular.
Anyone have any ideas?
https://stackoverflow.com/questions/60114758/uncaught-syntax...
Seems like it's not adding 'type="text/javascript"' to <script> in index.html. When adding this manually, everything works.
Just FYI if others upgrade and seem to get the same errors.
Modules, however, enforce strict mime type checking. As the comment below suggests, you should make sure your static file hosting serves JavaScript with the correct mime type.
Angular
React
Web Components
Things are changing so quickly, I just wanted to sort of have an overview for those of us who don’t work with these frameworks daily.https://blog.usejournal.com/web-components-will-replace-your...
Can Web Components pretty much do everything without a framework now? I think Ionic moved to it for example. If we already have our own code for loading and rendering components, using Handlebars templates, what would we need to do to make them into web components instead, or make all of ours compatible with the latest React or Angular?
The specifics for anyone who cares:
When we began our own framework, way before React and Angular, we built our own, kinda “sane” reusable component engine. We called them “tools”. One tool on an element is a component. But you could also add multiple tools on a component, to add or remove behaviors:
https://qbix.com/platform/guide/tools
Basically, we figured it would be easier to just let Templates, HTML, CSS and JS each do what they were intended for.
HTML side
1. We had <div class=“Q_Tool Streams_chat_tool” data-streams-chat=‘{“foo”: bar, ...}’> easily exporting json from php or templating engines, very readable and completely standard (no JSX or custom components). It was just slightly longer to write but provided useful metadata. It used to be called microformats back in the day. Multiple tools can be added on same element this way. The element didnt have to be a div.
2. We had handlebars helpers like {{&tool “Streams/chat” foo=bar}} and Q.Tool.setUpElement(“div”, toolName, options), or pass an element instead of “div” to add a tool on an existing element. We also had a jQuery fn method like $(“foo”).tool(“Streams/chat”, options).activate() .
3. Our users just called var element = Q.activate(Q.Tool.setUpElement(“div”))) in vanilla JS or $(“<div />”).tool(...).activate() if jQuery was loaded.
* CSS side*
1. We namespaced our CSS by Modulename_toolname_
2, Some tools took advantage of shared CSS classes defined in the module or a module they depend on
Javascript side
1. We just had Q.Tool.define(toolName, constructor, defaultOptions, methods) and the tool.state would be the options merged over the defaultOptions. It was all customizable and merging was done via a smart Q.extend() function that we tweaked to eg combine Q.Event handlers in the best way.
2. Ways to access tools on an element would include Q.Tool.byId() and element.Q.tools etc. The tool ids would be autogenerated so as to establish a hierarchy of which tool was a parent. Then you could do tools.children([filterName]) and tools.parents() and so on. Traverse faster without touching the DOM.
3. We had Q.activate(container, options) to activate tools within a certain container. Javascript for tools would be loaded on demand, and tools would be added/removed on demand. We had Q.Event.prototype.add(callback, key) take a String key or a Q.Tool, so events would be automatically removed when a tool was removed.
4. You could also do Q.Tool.define([toolName1, toolName2], toolName, constructor, defaultOptions, methods) to have tools require that previously named tools already be activated on the element. This is for composability of tools, something more general than inheritance. Let’s say you have a chatroom and you want to add support for @mentions to it and https://linkscraping.com as you type. So you’d make tools that work in top of Streams/chat.
It seems to me that ANYWAY your user will have to load a Javascript file that defined your web components. And ANYWAY they will have to load javascript on demand. And ANYWAY this javascript may be packed into a single file so you’ll have to actually check whether a variable has been set before loading modules dynamically so you dont want static loading. And ANYWAY your tools may want to use shared css so you may as well namespace your CSS. And ANYWAY your default options may include event handlers or other things you can’t serialize easily into attributes of an element. And you may want to compose tools or find them with CSS so what’s wrong with using CSS classes instead of the element name for that? And ANYWAY you will want to render your tools in a readable way so why not stuff JSON into data attributes which were allowed for exactly such purposes? And ANYWAY you may want to use a powerful templating engine like Handlebars. The only part I am not sure of is the last one.
Seems to me - but I am biased - that we have the optimal approach. If something else comes out we can just turn Q.Tool.define into a wrapper around window.customComponents.define. But our users won’t have to change a thing. They can continue to use Q.Tool and Q.Page and Q.exports(arg, arg) and Q.requires(module, callback) without worrying what’s underneath. Isn’t it better and more stable?
But everyone got into Angular and React with its JSX etc. I think the main sell was the dirty checking (the model in Angular, the DOM in React). So you can just render a large chunk. I never saw the benefit of that. You should reason about mutations imho. Components are views with their own viewmodel, that’s all. You can update a bunch of state parameters and then call stateChanged(“a”, “b”) which would requestAnimationFrame() and update stuff. Is it so hard to call stateChanged() after changing state.a and state.b ? Do you really need to instead grok digest cycles or a virtual dom??
Is there a standard way to define local variables in an Angular template so you don't have to repeat the same redundant expression again and again (or so you can at least give an expression a self documenting variable name so it's not so mysterious)? Or do you have to define an instance variable on your component and figure out how to initialize it to the right value before the template gets executed, with no way to lazily (or repeatedly) evaluate it by putting the calculation inside conditionals (or loops) in the template so they're not run if they're not needed (or to calculate the local variables independently for every loop iteration)? Is there an angular hook or technique that's meant for that, and efficient, and hopefully doesn't involve much arbitrary non-JavaScript gobbledygook syntax, and is at least somewhat standard and well supported? Please don't tell me I shouldn't ever want to do that for some reason of ideological purity or separation of concerns (as if a templating language could ever be called "pure" or "elegant"). The common legitimate use case is ngIf="some expression is not null" then {{some expression}}, and also ngIf="some expressions" ... ngIf="not some expression".
I googled for it, and the solutions of "abuse ngIf's special goofy syntax to name the result of the condition and pray to God it's truthy or don't bother" and "abuse ngFor to loop over an array of one item to give it a name" are not acceptable answers. There were also a few competing and possibly out-of-date "install this non-standard ngLet directive that I hacked up but don't support, but don't call it with an "ng" prefix because that's reserved for the Angular team" -- but isn't there a standard way of doing such a simple essential thing, that the Angular team already thought of and included, such that other people will have some clue what's going on when they see it? And it would be nice to be able to define more than one variable at once per begin/end tag, if you know what I mean. Maybe even without using any begin/end tags, perchance to dream?
Also, is there a way to easily define simple light weight macros ("snippet reuse") so you can repeat the same pattern in one or more components, without defining a whole component in all its glory and splendor with multiple files that other multiple files need to import and declare? Or even a global file of shared macros that a bunch of other templates can import, like the globally shared css declarations you can include in local css files? I've seen "ng-template", but I am having a hard time getting my head around it, compared to the simplicity and power of Genshi's py:match, that's based on xpath, and py:def, that precisely follows Python function calling conventions and that you can easily call from any normal expression. And py:match is quite useful for defining concise custom tags (or xpath patterns) that can wrap embedded content. In comparison, ng-templates seems quite clumsy and limited, and confusing about calling and scoping and passing parameters and content, which is nothing like standard JavaScript calling conventions, and reminds me more of the abomination that is Zope METAL templates.
https://zope.readthedocs.io/en/latest/zopebook/AppendixC.htm...
https://en.wikipedia.org/wiki/Template_Attribute_Language#ME...
https://en.wikipedia.org/wiki/Zope#Zope_Page_Templates
I've been using and loving Genshi with Python for more than a decade (and before that, Kid, which Genshi is almost the same as, and before that Zope page templates, TAL, and METAL templates, which inspired Kid and Genshi, but totally sucked), and I love its ability to drop into Python with <?python ... ?> to define some variables or import some functions locally in the template that you can use, with real honest to god multi-line indented Python "if" statements for logic (and Python comments for, err, commenting) instead of Christmas trees of deeply nested ternary ? : operators (or rather postfix conditional "foo if bar else baz" Python expressions). Genshi also has "with" for defining scoped local variables with tags, like <py:with vars="y=7; z=x+10">$x $y $z</py:with>.
And I also love Genshi's py:def for making locally defined or libraries of includable imperative "code snippet" templates you can call just like Python functions (with glorious optional named defaulting args, etc), and py:match for declaring xpath pattern matching templates that can wrap html content as a parameter (so the macro can cherry-pick out and transform different parts of the passed content with xpath), as well as taking attribute parameters.
Another nice feature of Genshi is that for all directives it supports both the attribute form like <div py:if="condition"> ... </div> attached to an element that you want to keep, or the element form that dissolves without leaving an element, like <py:if test="condition"> ... </py:if> . You can also attach multiple directive attributes to the same element, thanks to the way it executes them in a well defined ordered hierarchy that makes practical sense (like "for" above "if", so each iteration of the "for" loop can be conditionalized with its own "if" evaluation), and "def" above all else, so you can define a single tag macro that loops over something then conditionalizes each iteration, then sets attributes on and adds content to the included elements. It's quite concise and expressive!
<div py:def="FizzBusted(count)" py:for="i in range(count)" py:if="i % 3" py:attrs="{'class': 'orange' if i % 7 < 2 else 'blue'}" py:content="['odd', 'even'][i%2]"/>
https://genshi.edgewall.org/wiki/Documentation/xml-templates...
py:def
https://genshi.edgewall.org/wiki/Documentation/xml-templates...
py:match
https://genshi.edgewall.org/wiki/Documentation/xml-templates...
Processing order of multiple attributes (precedence rules you must remember, but they make practical sense, and at least Genshi is quite minimal and only has a few directives): py:def py:match py:when py:otherwise py:for py:if py:choose py:with py:replace py:content py:attrs py:strip
https://genshi.edgewall.org/wiki/Documentation/xml-templates...
These two features (local variables and code snippets) are so important to me, and I'm having such a hard time figuring out how to do them in Angular, that I feel like there's whole a chapter in the Angular templating manual that I missed somehow. Thanks for any tips on how to do this kind of stuff with Angular templates!
I've written more opinions about Genshi and templating on hn before:
https://news.ycombinator.com/item?id=8445252
https://news.ycombinator.com/item?id=10842990
https://news.ycombinator.com/item?id=12365442
https://news.ycombinator.com/item?id=12527839
https://news.ycombinator.com/item?id=16677520
https://en.wikipedia.org/wiki/Zope#Zope_Page_Templates
>Zope Page Templates
>As mentioned previously, Zope Page Templates are themselves XHTML documents, which means they can be viewed and edited using normal HTML editors or XHTML compliant tools (a big advantage compared to other template languages used for Web applications). Templates can also be checked for XHTML compliance so you can be fairly confident that they will automatically expand into proper XHTML.
I usually define something in the component, and reference that. If you need to lazily evaluate it you can just reference a function in the component (e.g. "...{{ someFunction() }}...", and have the function do whatever lazy work and/or memoisation you need there.
If you need things to be initialised before the template is ready, you can use one of the life cycle hooks - e.g. ngOnInit(). More details of the different hooks here: https://angular.io/guide/cheatsheet
... that said, it might be easier (depending on context) to "learn to love the bomb" and just rely on Angular's binding to update the template as soon as the value becomes ready after the template has rendered - i.e. don't sweat about getting everything ready before the template loads, just let Angular handle the data binding and let it update the tempalte when the value is ready. This is where the RxJS stuff really shines since you can forget about a lot of the sequencing and just let Angular handle getting the right value on the page when it becomes available. Unless you are doing long network calls or heavy computation, everything is usually in place by the time your brain registers seeing the page anyway so it mostly works out OK and no one notices any thrashing of templates going on under the covers (... although there is a part inside of me that dies when thinking about the performance/wasted CPU cycles).
> is there a way to easily define simple light weight macros ("snippet reuse") so you can repeat the same pattern in one or more components
I have also suffered this recently. I am not sure how this is "meant" to be done, apart from making everything a separate component. I guess the argument is, if you need to use something in multiple places then it is an ideal candidate to become a component. For these "lightweight" components I will usually just use inline templates for the component decorator (rather than referencing a separate HTML template etc), e.g.
@Component({selector: 'snippet-one', template:`<b>My First Snippet</b>`}) export class SnippetOne{}
You can put a load of them into a single "snippets" module, import the "snippets" module when you need it, and then simply include that where I need it in other templates with <snippet-one></snippet-one> and so on.I agree though that sometimes it would be nice to just have a file you can just easily drop in where you need it.
I'm currently subscribing to changes in a BehaviorSubject<any[]> instance variable of my selection service "god object":
selection service:
public user$: BehaviorSubject<any[]>;
my subscribing component: constructor(
public selectionService: SelectionService
) {
this.userSubscription$ = selectionService.user$.subscribe(user => this.drawUserInCanvas(user));
}
Is that a good way, or might I miss updates for changes to component instance variables and other reasons? Is there a canonical Angular callback that's recommended for stuff like drawing a canvas view after any changes have been made to the DOM?Thanks for the advice!
For your approach, that looks reasonable to me in the 5 lines we have to look at :-) ... so long as you are consistent with the SelectionService and make sure all the changes go through that, you should be fine and your component will get all the updates.
This sort of requirement for consistent management of things like this - i.e. the application state - is a weakness of Angular I think. It is easy to start simple and end up coding yourself into a corner with god services etc. I have used a thing called NgRx in the past for managing state - its the redux pattern and seems to be quite good at making sure state is a bit more sane and well-mananged in the app (at the cost of some boilerplate). One day I hope that there is an official state management mechanism.
I get the impression that <ng-template> is actually just directly exposing some low level implementation mechanism, and wasn't specifically designed to be a concise, powerful, general purpose, easy to use templating system, or behave in any way like JavaScript.
I keep trying to work my way through this otherwise pretty good tutorial:
https://blog.angular-university.io/angular-ng-template-ng-co...
>But besides that else template, the use of ngIf also creates a second implicit ng-template! Let's have a look at what is happening under the hood:
<ng-template [ngIf]="lessons" [ngIfElse]="loading">
<div class="lessons-list">
...
</div>
</ng-template>
<ng-template #loading>
<div>Loading...</div>
</ng-template>
>This is what happens internally as Angular desugars the more concise ngIf structural directive syntax. Let's break down what happened during the desugaring:>the element onto which the structural directive ngIf was applied has been moved into an ng-template
>The expression of
ngIf has been split up and applied to two separate directives, using the [ngIf] and [ngIfElse] template input variable syntax>And this is just one example, of a particular case with ngIf. But with ngFor and ngSwitch a similar process also occurs.
At this point I'm starting to feel dizzy, like when Scorpius needs his cooling rod changed.
https://www.youtube.com/watch?v=U7SS0YCWVGs
But when I got to the stuff about ng-template with parameter attributes prefixed by "let-", and tacking ";context:ctx" on to the template outlet name, and then having to stick some instance variable into your component source code (which is usually a separate file), my eyes glazed over and my palm hit my forehead. It's like learning a whole new set of cult-like jargon and mythological concepts (Outlets??! Why so many layers of indirection and different names for the same thing?), instead of reusing anything I already know about JavaScript, simply to pass parameters to a template. Maybe this is just a bad example and explanation of ng-template, but I haven't found a better one yet.
@Component({
selector: 'app-root',
template: `
<ng-template #estimateTemplate let-lessonsCounter="estimate">
<div> Approximately {{lessonsCounter}} lessons ...</div>
</ng-template>
<ng-container
*ngTemplateOutlet="estimateTemplate;context:ctx">
</ng-container>
`})
export class AppComponent {
totalEstimate = 10;
ctx = {estimate: this.totalEstimate};
}
That's how ZOPE METAL templates felt: it was such a big fucking ordeal to pass every single parameter through a named "slot", each wrapped in its own special outgoing and incoming namespaced XML tag, like COBOL with angled brackets. When it's all just clean simple Python underneath, but that's hidden from you, and you can't just use Python expressions and calling conventions, or XML attributes, or xpath, or define concise custom tags with attribute and content parameters, or write general purpose Turing-complete macros like Lisp.How do I make an ngFor loop iterate through a range of numbers, without actually defining a literal array of numbers in the component for it to loop over?
https://stackoverflow.com/questions/36354325/angular-2-ngfor...
With Genshi, you simply do it the standard python way, since Genshi for loops are equivalent to Python for loops: <div py:for="i in range(count)">$i</div>
But I can't figure out how to, for example, use ngFor to iterate from 0 up to n, since it requires an array argument, and there isn't a c-like form like for (init; condition; repeat), or a standard JavaScript way to make a range like python's range(n).
Should I just give up and make a "range" utility method on my "God" service object that I'm passing in anyway? The more gaps like that I have to plug with my God, the more it becomes a God-of-the-gaps object.