Just turn your app with pwa with
ng add @angular/pwa
Then you'll have acess to a services called SwUpdate
, with it, you can handle new version of you app whatever as you want.
For example, you could do something like:
import { SwUpdate } from '@angular/service-worker';
constructor(private swUpdate: SwUpdate) {}
ngOnInit(){ this.swUpdate.available.subscribe(() => window.location.reload()) }
Personally, I display a notification that - the App was updated in background and it's changes will take effect in next page reload - I also add a button with "reload now" option... since the user could lose data with the page reload.
But no, pwa it's not a overkill, pretty straigth forward. More info here.
Yeah, as /u/George_Rockwell said use Cypress. You'll never go back to Protractor. It's just a superior tool in every way.
Shameless plug since you asked for resources on E2E tests, I wrote a 500 page book on Angular and automated testing, The Angular Tutorial, which covers both unit testing and E2E testing using Cypress. It's currently the highest rated book on Amazon as well for books that cover Angular and testing.
The feedback I've received so far has been nothing but positive and I regularly release updates.
I mostly agree. I've said that the 3 best parts of angular are typescript, the di system, and rxjs. And ngModules by themselves are a bit annoying but they do multiple jobs and once you understand what you can do with them they aren't a terrible solution to a complicated problem.
There are some solutions to the library paralysis problem of react like next.js and I believe Uber recently released their framework that uses react as the renderer. But angular is still ahead a bit here I think because it's all designed together rather than developed separately and just glued together.
Personally though I disagree about jsx. Some things, like dynamic component layouts, are much simpler with jsx and in general I think it just feels nice to use.
But with the flexibility jsx brings it also brings the ability to overcomplicate templates as you are pointing out. It's a valid criticism where the best answer I have is "learn to not do that". It's not like people don't also write terrible angular components; it's just shifting the potential pain points.
I do agree that reacts biggest weakness is css. For a "view" library they certainly dropped the ball on one of the two fundamental parts of what a view is in a web browser.
The first one is property binding: https://angular.io/guide/property-binding
From the docs:
Property binding in Angular helps you set values for properties of HTML elements or directives. Use property binding to do things such as toggle button functionality, set paths programmatically, and share values between components.
The second one is called interpolation. When you use {{ value }},
value
is converted to a string, but there are times when you don't want the value of a property to be of type string.
Ex.
<input disabled={{ isDisabled }} />
vs
<input [disabled]=[isDisabled] />
disabled
attribute should be a boolean and not a string. That's when you need to use property binding and not interpolation.
Also, you'll use property binding for passing data (props as in React) into child components later in the documentation.
I am quoting this from Renderer2 api doc:
>Extend this base class to implement custom rendering. By default, Angular renders a template into DOM. You can use custom rendering to intercept rendering calls, or to render to something other than DOM.
The main thing is abstraction. By using Renderer you abstract the DOM, so you can target non DOM environments like server, native mobile etc. Basically for cross-platform capabilities.
That's awesome. Kudos to that wise manager ;-)
I've been on a few fast prototyping teams at my company, and with Angular, as one person I was able to develop web apps in a matter of weeks that the React team of 2-3 engineers would have taken months to do... while developing the backend in Node too.
Unfortunately the more established product at the company is written in React and the leaders want to consolidate around that.
As an aside I recently discovered NestJS and am loving it as a backend framework. It's basically a Node/Express framework that adopts a lot of the patterns from Angular. It rounds out the full stack very nicely.
props
and state
are not simply members of the component.Write clean code that is easy to understand. Commenting is, at best, a necessary evil.
Take this for example:
if((employee.flags & HOURLY_FLAG_ && employee.age > 50) employee.GetBenefits()
vs.
if(employee.IsEligibleForFullBenefits()) employee.GetBenefits()
Code can be self documenting; but it takes good craftsmanship and a lot of experience to make it happen.
I totally stole this example from the book Clean Code and its chapter on commenting, but it really drove the point home for me. Worth a read for anyone who wants to craft well written applications.
You should checkout Angular Elements: https://angular.io/guide/elements
With Angular Elements (web components) you can use your compiled app anywhere, basically.
After compilation you can concat your .js-files into a single file, if you would like to import a single script.
You should look for route guards, they work checking if a condition is met when changing to a route.
Take a look here.
Hope it helps :).
If you’re new, the official Angular Tour of Heroes tutorial is nice.
Also Traversy Media Angular crash course on youtube is great aswell.
Angular is similar to React anyway, you have ui components with inputs and outputs (events).
IMO the major differences are the templating engine vs JSX, and I find that people don’t use stores with Angular as much as people do with React.
TLDR: Don't do this.
The better approach would be to try and think about why you are returning HTML from the API? Is it because the backend service only knows about certain data? What if you converted this data to a more consumable format, like JSON?
If you could reason with what the HTML is supposed to represent, and then convert it to JSON, you could then construct Component's on the front end using the Dynamic Component Loader (https://angular.io/guide/dynamic-component-loader).
So, for example, let's say your JSON response was something like:
{ "div": "content for div", }
Then you could take this response and know to construct a div component, with the content for div inside of it. Which is a simple enough ng-content Component.
But, the hard part is going to be reasoning with this API, and figuring out what it's trying to represent, instead of just the raw HTML.
I use route module for every module that needs to handle its paths. I find it easier to maintain that way. Angular instructions here: https://angular.io/guide/router#milestone-2-routing-module
But really, it is up to you and how you like it. As long as you stay consistent throughout your application.
Sidenote: Angular.io recommends against filtering & sorting with pipes.
> Filtering and especially sorting are expensive operations.
https://angular.io/guide/pipes#appendix-no-filterpipe-or-orderbypipe
Just read the guide. It explains in detail how their releases work. It's how a lot of software is being developed these days including, but not limited to, most browsers, vscode, react (they are on v16 but you don't hear people complaining), and angular itself.
Honestly, I feel like at this point anyone complaining about a new major version number is most likely trolling. You don't see these complaints when react or vue announce a new release. At least not nearly as often, and definitely not every 6 months like clockwork.
Angular is just angular. It's on semver so angular 6 is just the latest version the same way that react is still react even though it's on version 16 now.
There are minor changes here and there but fundamentally it's the same framework.
So if you look for a resource you should prefer one that is 5 or 6 but information about 2 is still relevant and should be mostly correct. Most of the changes are just simple renames like <template> was changed to <ng-template>. So look for a newer resource first but a resource about angular 2 won't fundamentally be wrong but it might use slightly wrong names for some things.
Use the cli to get started and personally my advice is to begin with the official guide which covers starting with the cli and links to the official tutorial.
After that if you need more you could look into other guides but personally I'd start with the official stuff. It's always kept up to date and if nothing else is a good primer.
Every time change detection is run, your function will be called. If you log something out in the console within that function you'll see just how many times that is. An option you could use is ChangeDetectionStrategy.OnPush where change detection will check once.
Quote from typescriptlang.org:
> The default visibility of class members is public. A public member can be accessed anywhere.
> Because public is already the default visibility modifier, you don’t ever need to write it on a class member, but might choose to do so for style/readability reasons.
params?
this tells us that it is optional
: HttpParams |
says that the type of the params is HttpParams and then that pipe at the end says it could also be of a certain object signature.
Now let's break down the object signature
{ [param: string]: string | string[]; };
[param: string]
is declaring that this is an indexed object. This tells the compiler that the object will have some parameters on it that are type string, meaning the object should be accessed by params['TargetProperty']
just like in old school JavaScript. This is used because we don't know what parameters the user is going to want to pass in at compile time, so we can't define out the possible options.
And finally string | string[]
tells us that the value of the params key value pair should be either a string, or an array of strings.
To be honest, heavily relying on ng-deep
shows that your CSS might not be as structured as it should, and I believe that's one of the reasons why they deprecated it, because people tend to have parent components styling children ones, while they shouldn't, the child component should expose inputs ot edit theme if they want to be edited, that's it.
Also, they said they are going to drop support, not deleting it (see https://angular.io/guide/component-styles#deprecated-deep--and-ng-deep ), and finally, if you want all your css to just go trough everything, use a global css file that's loaded inside your angular.json configuration, or simply switch view encapsulation for the components you want to be higlhly customizable to ViewEncapsulation.None
.
I feel like you're trying to make Google responsible for bad design choices while there's plenty of possibilities for you to work around that and plan a migration on your style stuff for later in the project, I mean this has been deprecated for at least a year now...
Also, Google is open sourcing stuff so people can contribute and use it for free, because passionated devs will always be happy to help or even fix the stuff they don't like or found a bug inside of it. Every single framework, Open Source or not, has refactors, deprecations, and breacking changes, switching to another one won't change this.
It looks like you installed the old dependency angular2-material.
This package was used early in the pre-release development cycle of Angular Material v2, but has no longer been used since September of 2016. Development of Angular Material now occurs under scoped npm package @angular/material. Visit https://material.angular.io for the latest information and instructions for using Angular Material or check out the latest source code from https://github.com/angular/material2.
You need @angular/material
I forked + fixed your example
​
You had a syntax error in the template - missing `;` in the *ngIf
I also implemented the remove method. All it does is call 'next' on the text Subject with the modified value.
​
You are welcome :D
It's actually quite simple! I've done this previously. What you'll need are two things...
​
https://angular.io/api/router/CanDeactivate
Use this to determine whether or not you can move away from your page. Search around for examples using this. (Hint: You'll want to check if the form is pristine)
Second, you'll want to check the beforeunload event and verify that your form is pristine before unloading the page.
One of these is for when you navigate within the page, the other is for when you navigate using the browser back button or otherwise.
Look for examples using these two and you'll be golden. In all honesty, I may have googled with stackoverflow and found the solution through there. :)
Not a repo, but I always use the angular style guide by John Papa as a starting point for any style guides I use with teams.
https://angular.io/guide/styleguide
It is really good and has good examples of good structures and why they are a good idea.
For a repo, I would suggest any of the @ngneat projects. They are good libraries to be aware of and written by really talented devs.
So CORS is a browser thing. The way to get around it when you're calling an api you don't control, is to build your own api. If you have an app on a server calling an api on another server, there's no browser involved and therefore no CORS.
Then you just have to set the CORS headers on your own api and you're good to go.
For a side project or a small app, this can obviously be a bit of a pain. Lucky for us, Angular has built in support for a proxy server. That will reroute all your api calls through a proxy and bypass CORS errors.
If you're doing CORS with auth you might have to set the withCredentials
flag: this.httpClient.post('/api/scraper/scrape/', { urls: urls }, { withCredentials: true });
Also your request goes to "localhost:4200/scraper/scrape", looks like it's hitting your frontend? I think you might want a different URL there?
The async pipe will subscribe for you and pass the data that the BehaviourSubject holds to the child comp, not the subject itself. If you want to subscribe to the BehaviourSubject inside the child then skip the async pipe (not the best practice imo) or change the data input variable to the type the subject holds (ie any[]), and use ngOnChanges hook to reach the data in the ts file when it changes. https://angular.io/api/core/OnChanges
The mat-form-field component now supports 4 different appearance variants which can be set via the appearance input (legacy, standard, fill and outline). Here is a link to the page where you can find more info about it.
Basically, <ng-content></ng-content> is like transclude from Angular 1. Here is a plunker showing ways that you can use it.
So, lets say you have 'black-border', component, and the template looks like:
<div style="border:1px solid black"> <ng-content></ng-content> </div>
If you are using this black-border component somewhere else in your application, you could do.
<black-border> <h1>Hello World</h1> </black-border>
The "Hello World" would then be embedded within the <div> that has the black border on it.
You can also use selectors with ng-content, so if you had 'borders-component'
<div style="border:1px solid black"> <ng-content select="header"></ng-content> </div> <div style="border:1px solid red"> <ng-content select="div.body"></ng-content> </div> <div style="border:1px solid orange"> <ng-content select="footer"></ng-content> </div>
and in a part of your application it was being used like
<borders-component>
<header>I'm a header</header>
<div class="body">I'm a body</div>
<footer>I'm a footer</footer>
</borders-component>
The header would be inside the black-border, the body would be inside red border, and the footer would be placed inside of the orange border.
You need to import SettingsModule into the AppModule - since it's a feature module of your application and it is not lazy-loaded.
​
I added it to your stackblitz:
For the first example, the ToH is showing you the explicit version of how observables work but the majority of the time you will want to use the async pipe to get data from an Observable onto a template. I guess they want to show what's happening in the tutorial before showing the right way to handle displaying observable data.
The second example of injecting a public service is not something you will see very often. Since, unlike react, technically a template function isn't a member of a component controller class the values you want to bind to a template must be public. But in general you wouldn't want to expose a service to anything outside the component as it is considered an internal implementation detail.
Honestly, I haven't looked at it in a while and that part of the ToH tutorial is pretty bad. I mean it is properly showing the ideas off and how the parts are working. But it's doing things you are unlikely to ever see in a real app.
Functionally there's not really a difference between the 2 methods.
If you were to use the async pipe, as I mentioned above, instead of subscribing to observables manually then you get to set change detection to on push. That is a nice performance increase as you save on constant change detection cycles. But since neither method above is using the async pipe neither is currently able to use the on push method.
I'm not sure I really answered your question in my rambling above so let me just put it this way:
Both those examples are ok for showing how things work, but neither are the ways I would actually use Angular. So if I were you I would consider those more as explanations rather than proper usages.
I'm a bit confused... From the text it seems you are expected to somehow just make some adjustments to upgrade from AngularJS to Angular 10, is that it? Because that a herculean amount of work...
AngularJS (before 2.0) is simply not the same framework as Angular (2.0 and later) and while there are even some nice guides about how to migrate from an Angular version to a newer one, it's not that simple when it comes to AngularJS > Angular.
You could try this guide from the official Angular website, it offers some guidance of what to do (there are even ways to mix both AngularJS and Angular on the same application), but honestly, depending on how complex the website is you might as well just rewrite the whole thing, there's no way a complex application made in AngularJS can simply be "converted" to Angular and result in good code.
Learn how to deploy any static website first. https://css-tricks.com/deployment/ is a good place to start. I always recommend people to start with the basics first rather than jumping on a framework and wondered where they are years after. I looked at your repo and to be honest, you don't need angular 2 for this. I might be wrong and you might be adding more features into it in the feature which justifies your choice of framework now.. but for a static website with 4 pages, come on.. even if you really want the website to be SPA, vanilla js is more than enough for this. Heck, you might be learning more stuff (AJAX, Dom) than you do with angular 2. Learn how to make html pages, webservers and where do you go to host them etc. if you're already using github, take a look at github pages https://pages.github.com . Angular 2 compiles to html, js and css so it's pretty much static website. Now when you're ready, start on more projects that angular 2 is more geared to, which is web apps.
A few of mine:
I prefer going all in with ngrx state for moderate to highly complex tasks just for consistency. It does make extra boilerplate though. I find projects that mix state between ngrx and elsewhere can get awkward to know where state lives for any particular thing or you end up refactoring later to bring things into ngrx. Always tradeoffs.
async pipe doesn't need to be unsubscribed. You can also avoid dependent observable subscriptions by pooling all observable in a global async pipe - https://stackblitz.com/edit/subscribing-to-multiple-observables?file=app%2Fasync-pipe-object%2Fasync-pipe-object.component.html
don't create new mapped observables in getters, each time the change detector runs, it will create a new subscription because each time it runs, a new observable is created by the getter... instead, assign mapped observables to instance variables/properties...
Typescript allows you to explicitly cast a value to another type, even if it is "wrong", due to the way js works and the ts teams' stated goal to allow all existing js patterns to work in ts.
Anyway, you really shouldn't cast anything in typescript. Casting should be seen as an absolute last resort. I can't think of a single place where casting is needed but I don't rule out one exists. Most of the time when you think you want to cast you actually want a type guard.
Discriminated unions are great. Just don't use them to try to hide information about the original source data. DUs should actually describe the different shapes of data something will accept or return, not act as some sort of type security layer.
In addition to that, a directive might be useful if you don't want to tie the functionality to the class. In this case, an attribute directive seems fitting. You could modify the parent using the native element reference and also listen to the events.
https://angular.io/guide/router
You're asking for a few hours of research and reading which is difficult to summarize here. I'd read the link above to get a handle on Angular routing.
I feel like I need an explanation or some sample code here. My first thoughts are "ngIf"
<div *
<code>ngIf</code>="condition">Content to render when condition is true.</div>
and if you were trying to show/hide a component based on some boolean condition:
<ng-container *
<code>ngIf</code>="condition"> <component-selector></component-selector> </ng-container>
You can! check out preloading and custom preloading strategies!
I'm guessing you have a router outlet on your component that is doing some navigation which adds a location state to the router. If you identify where you're doing extra navigation, you can add the skipLocationChange parameter to the navigation so you don't have an extra history location: https://angular.io/api/router/NavigationExtras
That's a blast from the past. Yeah that's outdated, typing are more automatic now.
Save yourself a lot of trouble. Follow the quickstart guide and use the cli as per the instructions there.
Well to answer the simplest form of your question, you can use (click)=functionName
directive to perform an action when clicking on a div, just add it to the div elements.
I would also refactor your template to read from an array using *ngFor
and then create a typescript class for your EstimateOption
which contains a title, sourceImage, and click action.
Further your selection could be leveraging the router and child views and filling in each view based on the content rather than showing and hiding with *ngIf
.
Anyways stuff to look at later, but you're probably looking for <code>(click)</code>
Lets say you have a component to show the details of a hero (just the name for simplicity)
@Component({
selector: 'hero-detail',
template:
{{hero.name}}
})
export class HeroDetailComponent {
@Input() hero: Hero;
}
You can show this component in another page by just simply using its selector
@Component({
selector: 'heroes',
template:
<div *ngFor="let hero of heroes">
<hero-detail [hero]="hero"></hero-detail>
</div>
})
export class HeroesComponent {
public heroes: Array<Hero> = [{name: 'Superman'}, {name: 'Batman'}];
}
The 'ngFor' here is a simple for loop for all the items in the 'heroes' array, so this will render the hero-detail component two times once for Superman and once for Batman.
The [hero]="hero" parts sends data to the input (@Input() hero: Hero;) of the hero detail component.
You should really read the getting started tutorial about this subject!
By making the browser do the conversion from Typescript to Javascript, it adds an extra steps, which means an extra delay before the browser can process the scripts and display your application. This is fine on Plunker, as it's a developer tool, aimed to help you quickly test things, and therefore you don't want the extra step of compiling the TS to JS each time.
When you're packaging an app for production, it makes sense to do the compilation at that point, and deploy your app with the already compiled JS.
As for development, you can use npm start to launch a server and compile TS to JS as it detects changes, so it's almost a seamless process
https://angular.io/docs/ts/latest/quickstart.html#!#package-json
Shameless self-plug here but I wrote a 500+ page book specifically about Angular and automated testing with Karma/Jasmine and Cypress for E2E.
It's currently the highest rated book on Amazon covering Angular and testing. All of the feedback I've gotten so far has been very positive, both on Amazon and from direct communication.
If you'd like to learn more about my book you can check out the website here.
You can also ask me questions directly here and I'd be happy to answer them :)
Trying to separate code into libraries and the horrible development process / inner loop (link).
The need to stop an ng serve
after a library change/rebuild is terrible. I've moved to NX which solves that problem but nx workspaces only work in a mono-repo, so if you have a framework in one git repository and an app in another, you can't use the framework libraries in the app without the same stop/restart of ng serve
.
ng serve
really needs to handle the building and rebuilding of libraries and synchronizing that with restarting/updating ng serve
so we don't have to pay the startup cost of ng serve every time a library changes.
Alright, the variety of concepts you’re missing here is pretty large. But that’s okay! Everyone is new to programming at some point.
The two things you need to understand are modules: https://www.typescriptlang.org/docs/handbook/modules.html and dependency injection: https://angular.io/guide/dependency-injection
Learning Angular is tough if you haven’t learned: - simple programming - medium understanding of Typescript in particular - the frameworks/libraries which underpin Angular, like RxJs for example
However! I will try to explain the difference
In JavaScript (which TypeScript transpiles to) combining multiple files of code together is done by importing modules into other modules. TypeScript has the same concept. When you’re writing import, you’re importing code from one file into another file.
However, Angular also provides another mechanism for sharing code throughout your application, called Dependency Injection. Dependency injection occurs at runtime, whereas importing occurs at compile time. The one thing that makes dependency injection tricky to understand in Angular is when you import something in an NgModule, you’re telling Angular to provide that thing at runtime. So in the case of importing FormsModule in your app module, you’re telling Angular to make the stuff inside forms module available when the app runs. This isn’t really what the non-NgModule imports mean, they mean “include the code from this file into my file at compile time”
If this is the type of thing you’re struggling, with in Angular, I would recommend studying some fundamentals first. Maybe learn to write some simple JavaScript programs? Move on to getting a handle on TypeScript. Then give Angular another crack?
https://material.angular.io/components/dialog/api
I'm not very familiar with angular material, but it looks like you could try to listen on backdropClick observable and manually close it if you don't find a different way to get the css without pointer-events: auto. Might just be a bandaid fix but something to try
When it comes to having both web and NativeScript code sitting in the same project, then we use a naming convention, for example: - home.component.html - for the web UI - home.component.tns.html - for the {N} UI Then you just need a build system that can pick up the right file when building the web or mobile project.
You can read more about it here: https://www.nativescript.org/blog/code-sharing-between-web-and-mobile-with-angular-and-nativescript
Can't share it because it's practically owned by my company, you can look however at http://plnkr.co/edit/GJTLrnQdRDBvZenX59PZ?p=preview by user zoechi. As an added bonus, his work is done with TypeScript, I've used pure ES6 because of workplace requirements (his code is more concise for it).
This is very common, and 100% doable.
Check out this stackblitz: https://stackblitz.com/edit/routing-layouts?file=src%2Fapp%2Fapp.module.ts - Essentially what it is is for every Module / component you give it a layout to load when initializing it via the data property. This makes apps extremely flexible. With this approach any part of the app can have a different layout if needed. This is the approach that I am using.
Depending on the sizes of your app, I would also recommend separating your apps apart. You could do an app, and an admin app. Angular CLI now lets you create multiple apps in the same project. You can also have a shared project for stuff that needs to be shared.
Controls can be dirty. I made a little stackblitz example: https://stackblitz.com/edit/angular-diffed-form-example-for-reddit
I used a filter over a FormArray
to only return the controls that are marked dirty. This logic is very crude but it gets the point across.
TypeScript is 100% a language, what? Literally the first line on their github: "TypeScript is a language for application-scale JavaScript. " That would be the same as calling C# not a language because it gets compiled to IL.
You can create custom method decorators: https://www.typescriptlang.org/docs/handbook/decorators.html#method-decorators
In all but my first Angular 2 projects I've used Property Decorators to hold meta-data on model properties (htmlId, disabled, minlength, maxlength etc.). Here is my working demo of creating a custom property decorator. The first time it proved to be quite tricky so I made this sample in node:
https://github.com/PaulLockwood/TypeScript-Property-Decorator-Example
Component Interaction in the official docs:
So, the short answer is that it's possible. The longer answer is depending on the complexity, it can be done with only a fair amount of effort.
First question, does the user need to login to access your suite of products? If so, then I would suggest a JSON Web Token with cookies to have the token work throughout the suite of products.
Secondly, you would need to serve each product as its own app and can route to it via ngZone (at least this is what we use at work). ngZone is super cool because it let's you do stuff inside or outside the Angular zone, and you can Google around to understand it better than I can explain it here.
So, to oversimplify the process what you would do is have have all the projects in one code repo that way you can import the modules from other projects, this goes into a better explanation of the above
Hope that helps.
I am sure.
https://angular.io/guide/deprecations#http
Didn't affect me but it's the most significant breaking change. It's been deprecated since Angular 4/5 though hasn't it?
It is not recommended to use pipes for sorting or filtering as explained here https://angular.io/guide/pipes#appendix-no-filterpipe-or-orderbypipe
Your other questions strongly depend on your specific use cases. In an application where you typically navigate from a list to another page and then back to the list, as a user I'd expect the list to be sorted as I did before.
The async pipe is your friend when putting observable data onto a template.
In short, given an observable in the component controller:
data$: Observable<{ name: string, list: string[] }>;
Then in the template you can do something like:
<ng-content *ngIf="data$ | async as data"> <h1>{{data.name}}</> <ul> <li *ngFor="let item of data.list"> {{item}} </> </>
You can either organize where the router outlets are in relation to the rest of the content or you can use secondary routes.
For the first choice say you have a map url where you are displaying a map and have a side menu. Basically you describe the route as something like this:
{ path: "map/:id", component: MapLayoutComponent }
So then MapLayoutComponent might have a template that looks something like:
<div> <sidebar><router-outlet></></> <map></> </div>
So here I'm embedding the router outlet inside the sidebar. Then in order to change What's in the sidebar you can define that inside child routes of the map route:
{ path: "map/:id", component: MapLayoutComponent,
children: [
{ path: "", component: ListViewComponent },
{ path: "details", component: DetailsViewComponent }
] }
Then when the user is on /map/123 the route inside is bound to the sidebar's content and displays the ListView and if they somehow navigate to /map/123/details the DetailsView will be shown instead inside the sidebar.
The second option using secondary routes is the same basic idea just using a secondary route so that the main routing actions of the url can be used for other things, say in case the main url is being used to control the map itself. But fundamentally it's the same basic idea.
100kb should not be a deal breaker. Think of it as one more hero/jumbotron/banner image added to the page.
Angular also supports lazy-loading modules based on route: https://angular.io/guide/ngmodule#lazy-loading-modules-with-the-router
I do not know enough about Vue to know how much support there is for that.
you are almost right, the syntax is
<div *ngFor="let user of users"> <div>{{user.firstName}}</div> </div>
I'd suggest to work through the tutorial if you are new with Angular: https://angular.io/tutorial The [ngForOf]-syntax is explained in chapter 3 ;)
If you are attempting to test a component that contains a nested google-map component, then I would recommend using a stub in place of the google-map component. See this part of the Angular documentation: https://angular.io/guide/testing-components-scenarios#nested-component-tests
One thing you didn't specify is whether the second app is for a different client. If that is the case, keep those projects as separated as possible to avoid embarrassing errors ("why is x company's logo showing up instead of ours?").
Git branching is one possible option. Just create another branch and strip out everything not needed.
The more robust option would be an Angular "library project" for shared code. The library can be utilized by:
You don't necessarily need a monorepo -- but depending on your needs it might make your life easier. Similarly, you don't need nx to create a monorepo -- but it might make your life easier (if you agree with its opinionated structure).
Been a bit. But i believe this should help
https://angular.io/guide/router
Should be as simple as defining the path you want. And the component you want to render (and output)
Its been a while since i did it though
Yeah, it's a code smell. As others have pointed out - one way data flow. Do not modify an input you get. It's troublesome at best, and causes bugs at worst.
I want to throw one more possibility in - next to working with a copy and two-way data binding with post and postChanged methods: The ControlValueAccessor (https://angular.io/api/forms/ControlValueAccessor)
Forms are one of Angular's way of modifying data (while keeping track of changes and sticking to one-way data flow principles). Now, for your use case, it might not be the way to go, but I think it should be mentioned. It allows you to expose the post
as something to be modified, and you can then use either [(ngModel)]
binding or use an actual FormControl
to keep track of your data and changes.
i've heard they changed something about internationalization.
so what the current state of the art to implement this?
can i follow this https://angular.io/guide/i18n or will it be deprecated soon?
In style guide, the services are singular and folders are plural... but the truth is, go as you please, there's absolutly nothing to gain with this kind of discussion, only loose (time).
Personally I like having all singular.
If the error CSS classes are rendered based on invalid and touched form controls instead of just invalid. Or if you mean why loop over them instead of FormGroup#markAllAsTouched, I left a comment about that on Medium.
Are you referencing val.sub
in the header markup? If so, you may want to use the AsyncPipe so that Angular knows the value is asynchronous and won't try to evaluate sub
until val
has loaded.
Good on you for being willing to learn something new (even if it's the anti-Angular...)
Whenever someone's learning something new, I always prefer to recommend that they start with the official tutorial. In the case of React, it's right here, and it's really good. It doesn't cover a lot of the complications that will come with trying to use React as a framework - how to make AJAX requests and populate React components with the results, routes, etc. - because all of that is actually outside the scope of React. You'll probably end up using react-router and axios, and a bunch of other libraries cobbled together in varying degrees of integration, but you'll need to learn those separately.
One great thing about learning React: You will be forced to structure your code well, laying out your components logically and carefully, or it will be a hairy mess. Unlike a real framework, like Angular, React imposes no particular structure of its own. You can get as messy as you like with it. Want a 10,000-line monolithic JavaScript file with everything in it in, y'know, whatever order? Like the bad old days of JQuery? Well, React won't stop you.
So you'll be forced to stop yourself. Which is good practice.
It's absolutely possible. I've done it multiple times.
Check Angular Material Documentation
Look for the table example 'Table retrieving data through HTTP'.
One thought I have is to use the angular/cdk's portals https://material.angular.io/cdk/portal/overview
This can also be achieved with angular/core's ComponentFactoryResolver, but not as easily.
If you are going Angular, use Angular Material for styling. It is one of the best for Angular atm and fits well with the component based architecture. https://material.angular.io/
As for learning Angular, what /u/mdpotter55 said is a good resource. There are also a bunch of tutorials online. I highly recommend reading up and doing some tutorial projects so you can get familiar with typescript and the other parts of Angular you probably haven't dealt with before.
well, i'm not familiar with gwt, but it looks like it's attempting to offer a lot of the same type of functionality that angular does, namely view templating and rendering. it also gives you access to a suite of ui controls which would be somewhat in-line with what material (https://material.angular.io/) is trying to do.
trying to combine the two is probably always going to be hacky on some level. if you want to get rid of gwt, you would just rewrite all of your site to use angular. depending on how much of gwt you use, this could be relatively straight-forward or a nightmare.
I have run into this request so many times because our customers LOVE their pdfs for whatever reason. My comrades and I have tried repeatedly to get it looking good cross-browser on the front end and it's just way too labor intensive.
We've finally settled into doing it server side with puppeteer.
We have a node REST API service we keep stand alone only for pdf generation. We typically use React on the front end but I see no reason this can't work with Angular. Here's our flow:
Pretty simple overall. Puppeteer has a great API and documentation, and does better at consistently creating well formatted pdfs from HTML & CSS than any other method we've used. It's minimal effort. Our clients get their pdfs and are happy. We don't have to work to hard to do it so we're happy also.
Rather than subscribing, you should look into using switchMap or mergeMap (known as ”higher order observables” via pipe. Ideally, you should very rarely be subscribing to your observables at all; rather, you should be unwrapping them via the async pipe in the template. If you have an egghead.io subscription, I highly recommend André Staltz’s RxJS courses. This stuff hard learn, but worth your time. He has a whole course on higher order observables.
I'd recommend Cypress for E2E testing.
Shameless plug but I also recently self-published a book that teaches you automated testing, including E2E, in Angular.
Here we go:
http://plnkr.co/edit/RO5GZYgfEmbbEnZLbxSU?p=preview
Rather than using the items
I was talking about previously, I changed your model
into an arraymodels
, as I thought it might be easier to understand.
I've tried to add comments to explain the reasoning behind most of the changes - any questions or further explanation you want, ask and I'll try go into more detail.
You should really be bundling your app with System Builder or similar. You could do it this way, but it might be easier to configure System to know about @angular
imports and do the right thing. Check out the way the Angular2 plunk template does this in config.js
.
I'm a newbie with angular 2 and typescript, but i've used rxjs observables alongside angular 1, so i took a shot at it. Here's the plunker of my implementation: http://plnkr.co/edit/4eI5ce0iS6G69FzHNfEH?p=preview
I updated getPersonById in service.ts to use angular 2's Http service. It gets from a rest api, then when it gets the response back, maps it into an object matching the person interface. I did not update getDepartments.
In form_edit_component.ts, the ngOnInit function synchronously sets the model to an empty object, then calls getPersonById, and when it receives the response, updates the model.
Some small changes were made to main.ts and app.ts to import stuff related to http and rx.js
EDIT: though it's currently not being executed, i also modified your createObservable function to use some of the built in observable functionality and thus be just a one-liner.
Definitely possible. Here's a quick and ugly example of one way to do it:
https://stackblitz.com/edit/angular-ivy-tj9ubc?file=src/app/app.component.html
This is a shitty example and definitely not ideal and like other users have pointed out it's probably best to go the directive or component factory route.
Yes, you should put the todos in a service. As u/vicmarcal said, using a Subject will simplify the code. Basically you do all the data fetching and manipulation in the service, and then you "emit" the data. The components listen to those emissions. It's a bit like an event emitter, you had the right idea.
Here is a small example.
You can run GitHub repositories created with Angular CLI in StackBlitz.
stackblitz.com/github/{GH_USERNAME}/{REPO_NAME}
https://stackblitz.com/github/cu0ngpitt/weather-app
Some bug with newer CLI projects though but adding this to polyfills.ts should fix it:
import 'core-js/es7/reflect'
I've forked that StackBlitz and made some changes on it. It doesn't use the share() operator, but it will call the service only once. Also uses the async pipe and filters the response by the query string.
Straight way without infinity scroll looks like this
https://stackblitz.com/edit/angular-more-data-from-list?file=src%2Fapp%2Fapp.component.ts
you can trigger nextPage() on scroll instead of button click
I wish I had this when I was studying. Angular Material Table with Search, Checkboxes, etc I'm slowly adding features to it to help others and I refer noobs to it almost every day. You can fork it and add more of what you want to teach and go from there. Connect to Firebase, set up on AWS, add Nestjs / TypeORM on say Postgres, that sort of thing besides features.
I would avoid the books. They are often obsolete and go too detailed into each topic. Learners need the big picture and they need relevancy. Learning CRUD and setting up a DB / server will get them excited. They can dig deeper later. Don't take shortcuts like Mongo without next setting up a server even if they have to copy all the code. Get them to CRUD ASAP. Fill in the gaps later.
Aight I'm going to do a top level comment with a full explanation. When I tested the example again, when one select value changed, it was changing other selects too even though the array was functioning properly. This lead me to beilieve that angular was having trouble tracking values in the array.
Therefore, I provided a track by function for angular. New ngFor, sorry i'm not used to templates, just used a div
<div *ngFor="let t of contactTypes; index as i; trackBy: trackByFn">
I made an update to the binding of the select box, although this might be unnecessary, it's good pattern to perform side effects on select box change.
<mat-select name="{{i}}" [ngModel]="contactTypes[i]" (ngModelChange)="contactTypes[i] = $event" placeholder="Contact type">
Full code including track by function is here. https://stackblitz.com/edit/angular-material-bcgfnf?file=app%2Fapp.component.html
Saying that primitive types are not change detectable is a pretty big statement, and brings into question the usefulness of the framework. I don't believe it to be true in any way. After all, objects are just wrappers around primitives.
Also, according to u/talleane, angular runs change detection on the entire DOM on each triggered event, therefore this is not a good pattern in terms of performance. Instead use OnPush change detection.
I took the chance to provide an example of ReactiveForms that solves your problem since it is the preferred way to do forms in Angular6 at this point.
Forked stackblitz: https://stackblitz.com/edit/reddit-generated-form-controls
I tried to comment things to clarify what I was doing if you haven't used ReactiveForms before. If you have any questions feel free to ask.
Might be a better way to do this, but I'm too tired to bother any further.
Aslong as all of your Components are defined inside the app then you can do something like this
https://stackblitz.com/edit/angular-dynamic-content-viewer?file=app%2Fapp.module.ts
If you need any more than that then I think you want to wait for Angular Elements
Use this online IDE for learning purposes, you don't need to install anything on your mac/pc: https://stackblitz.com/edit/angular-rocmr7
As for your difficulties learning Angular, you'll just have to power thought it man, like everyone else, Angular is not easy to learn, but the payoff is worth it, it's a very powerful framework, a lot of companies are also looking for a good Angular devs.
Personally I started learning Angular though Max's Udemy course (it's 15 bucks or something), a few courses every evening before going to bed, then started building things with it even if they sucked, but though iteration, failure and looking how other devs do, you learn, it's a normal learning process, don't worry you'll get there.
Materialize CSS is designed to be used with anything else. Like if you have some HTML and want to do some styling. Don't expect it to offer powerful UX components. Materialize is just not powerful enough as a UX library.
Material the official library has a nice side bar implemented in Typescript. It is also tested for evergreen browsers.
If you build an Angular app, use Material.
You should be storing dates as a Firebase Timestamp[0] and view the date with the filter pipe like this:
​
{{ date.toDate ? (date.toDate() | date: 'shortTime') : '...' }}
​
[0]: https://firebase.google.com/docs/reference/js/firebase.firestore.Timestamp
You can use abstract class and put common methods and properties in it. Then make your specific component class extend the abstract class - it will inherit common stuff.
If you’re really new, the official Angular Tour of Heroes tutorial is nice.
Also Traversy Media Angular crash course on youtube is nice aswell.
For lifecycle detail, see the Angular docs .
But basically, Angular will call your "hook functions at eight various times in the components life - and for every one of those you want to get a call on, the common practice is to "implements" an Angular-defined interface. For example, for initialization you "implements OnInit" which then requires you write a function named "ngOnInit" So, if you want to be notified and given a chance to take action at multiple points in the component's lifecycle, you'd implement multiple interfaces. (Phone screen next questions is going to be "is that required" - no, the interface is actually optional, Angular will find the ngOnInit() if it's defined even without the "implements OnInit" but if you don't define it you're robbing yourself and your tooling of a valuable clue...)
Configuring webpack (https://blog.sicara.com/a-progressive-web-application-with-vue-js-webpack-material-design-part-3-service-workers-offline-ed3184264fd1) is easier than ng add @angular/pwa --project my-project
(https://angular.io/guide/service-worker-getting-started)?