Angular universal alternative to queryselector - javascript

All the plugins which are currently supporting angular 2.0 don't seem to support Angular Universal. It shows errors due to the direct DOM access. I want to alter the DOM access code in the angular 2 way. Can anyone suggest the angular 2 way for window, document,queryselector(), querySelectorAll(), document.getElementsByTagname(), getElementsByClassName(), etc.

At first, direct DOM access is discouraged in Angular2. You should prefer using directives like *ngFor and custom structural directives to update the DOM.
You can use one of the methods mentioned in angular 2 / typescript : get hold of an element in the template to get hold of an element and use what the Renderer provides to modify the DOM without breaking Universal.
For structural directives see also
https://angular.io/docs/dart/latest/guide/structural-directives.html

Direct Dom access is discouraged in Angular. Also, you can see comments about using elementRef. elementRef is also discouraged. For elementRef, Angular teams says:"Use this API as the last resort when direct access to DOM is needed.".
You can use renderer2 library. Use this library with elementRef together.

Related

Angular 7 -what is mechanism behind creating components with isolated scope with styles in angular?

In angular 7 - does core library using shadow dom element to handle isolated scope. what is scene behind the creating components in angular 7 and how isolated scope its working ?
can anyone please help me to understand this ?
In Angular default view Encapsulation technique is emulated, which is provided by encapsualation: viewEncapsulation.Emulated , you don't have to explicitly define this. This emulate Native scoping of styles by adding an attribute containing surrogate id to the Host Element.
If you are using encapsualation: viewEncapsulation.None, this doesn't provide any template or style encapsulation, whatever the styles you define, will be applied globally.
If you are using encapsualation: viewEncapsulation.Native this will use the native Shadow DOM technique, but all the modern browsers does not support this.
As per the document of angular, DOM encapsulation is used for component-specific style inject.
This seems to be the key feature like creating a pseudo element and attaching the styles in the name of it.
MDN-Docs
Angular-Docs
Update
Found this in angular's official repo: style_compiler
need to study deeply though!

jQuery functions in Vue components in Quasar-Framework

I'm new to web app development and I have some basic queries about jQuery and Vue, the answers to which I just can't seem to find. I have an app made in a Quasar-Framework which often uses functional references like:
- {{ $t("refer to some variable in another Vue component") }}
- $v.form.username.$touch
- $customVueComponent
- this.$q
etc. These are used both in the "template" and "script" sections of the Vue components. I am familiar with Javascript (or so I thought I was) but don't know much about jQuery. As far as I understand, these functional references are built in in jQuery and are somehow referencing some internal functionality.
It would be great if someone could explain what exactly these '$' references mean, how they work, how to use them and if there's comprehensive list of these functions to refer to.
Thank you very much
I am no expert but I've been working with vuejs, jquery and quasar for a while so I think I can help you with some of your doubts.
About jQuery and VueJS
First I'd like to say that using jQuery with VueJS is generally seen as a bad practice for VueJS developers (you can use it as long as both aren't touching the same things especially events and DOM and that you consider that you MUST use it for a certain part of your application).
The reason to this is that the way Vue works creates conflicts with jQuery's manipulation of the DOM and events. VueJS life cycle works in a way that the DOM, where Vue is attached, gets updated pretty often to match what the instance has defined (reactivity. This means jQuery may lose track of events bound inside this context resulting in bad synergy between the two.
Another thing is that basically anything you can do with jQuery you can already do it with Vue + plain Javascript so I only recommend using jQuery if you find it neccessary, like it was already in this old webpage you developing or because you must use a certain jQuery plugin in an already Vue-only application. For this you'll have to create separate components for each functionality you want to reproduce with your jQuery plugin with a combination of props, data, mounted and watch, basically updating the plugin manually.
About the $ sign
So about this $ sign. It's normal that you confused it with jQuery as '$', in the previously mentioned javascript framework, works as an abreviation for jQuery.
For example you could either:
jQuery("#test").val()
or simply do this instead...
$("#test").val()
So that's for jQuery.
$ sign in VueJS and Quasar
This $ sign is used in front of the name of properties or methods which the vue instances and components have by default.
If you've been using vue for some time you'd notice that if you want to get the reference for a particular part of the DOM or for a component you'd set a ref to it then call it using the $refs property of your Vue instance. This $refs property is a base property of Vue instances.
There are also others like $data, $options, $el, $emit, $watch, etc. You can find more related to this properties and how VueJS uses proxying for things like $data in this article.
Since Quasar is a VueJS framework and we know that using jQuery in VueJS isn't generally seen as a good practice, we can safely assume that Quasar devs uses this symbol for something else and not for jQuery calls. Something like naming prototypes/base objects.
In the example you gave
$t is often used for Vue-i18n, an internationalization plugin. You can see about it in Quasar's page here
$v is used for Vuelidate, a plugin for validations in forms. In Quasar's Documentation there is a page dedicated to it here.
$q is quasar's base object where you can call certain plugins from them like Notify:
this.$q.notify.create('Danger, Will Robinson! Danger!')
You can also set sessionStorage, localStorage and call other prototypes which are injected as said here.
tl;dr: $ is used in jQuery to abreviate the jQuery call. jQuery and Vuejs together are generally seen as a bad practice but it can be done. Quasar is a VueJS framework so it is developed using Vuejs + plain Javascript. Properties with '$' at the start of their name are prototype properties, methods and objects from both VueJS and Quasar that are repeated in every Vue instance and Quasar pages and have a purpose like easily accessing the data of a component, calling a plugin or emiting and event to the parent component.

Use of Plain JavaScript in angular5

Use of Plain JavaScript ( syntax like getDocumentById) in angular5 project is good coding practice or not , or Should we use ElementRef , TemplateRef , ContainerRef for referring the DOM elements instead of Plain JavaScript.
It's not encouraged to use the DOM element manipulation directly .
This blog explains why it should be avoided
With Angular 6 last update by google they have started moving towards shadow dom and dom hierarchy tree it would help dev community to not worrying about actual dom elements manipulation
Use the framework, don't go direct to the DOM (which is what you mean by "plain JavaScript") unless you have no other choice. (Or don't use a framework at all.)
But note the warning in the ElementRef docs:
Permitting direct access to the DOM can make your application more vulnerable to XSS attacks. Carefully review any use of ElementRef in your code. For more detail, see the Security Guide.
If you can avoid using ElementRef (without going direct to the DOM), that's probably best.

Accessing global objects with angular

I want to know the best way to access global objects and emit some events on these objects in Angular App things like ( window, local storage, document or any other purpose)
and is it right to call it like a JS object or should I stick to the Angular way of doing so?
and if I'm not allowed to manipulate DOM with any other library like jQuery in an angular app?
The most common way is to use services to keep track of objects around the app. Wherever you want to access some data, you simply just inject that corresponding service. You can read more about services here: https://angular.io/tutorial/toh-pt4
When it comes to DOM manipulation, Angular have their own functionalities for communicating with the DOM. For example you can manipulate the DOM using the built in Renderer2. You can also get access to the nativeElement of some element reference. It's not recommended to manually update the DOM with Vanilla JS or jQuery.
Renderer2: https://angular.io/api/core/Renderer2
ElementRef: https://angular.io/api/core/ElementRef
I would advice the following:
Don't access the document object for DOM manipulation or use JQuery. Angular itself provides all the methods required in order to manipulate the DOM. Using Angular and JQuery in conjunction would be an antipattern (IMO).
Here are some tools in Angular which allow you to manipulate the DOM:
Template syntax, For dynamicallly outputting html text
NgClass, For dynamicallly adding strings
*NgIf directive, for conditionally showing certain DOM elements
Renderer2, for Doing all sorts of DOM manipulation.
Things like localstorage and sessionstorage you can directly access from your angular application.
For holding your global data I would advice you to use services which allows components to easily share data between each other.
Of course you could in theory add jQuery or another library for DOM manipulation but this defeats the whole purpose of using Angular in the first place. Since we want to use Angular for creating SPA's application in a relatively easy manner.

Components and directives in angular 1.5

The big feature changes in Angular 1.5 are surrounding the support of components.
component('myComponent', {
template: '<h1>Hello {{ $ctrl.getFullName() }}</h1>',
bindings: { firstName: '<', lastName: '<' },
controller: function() {
this.getFullName = function() {
return this.firstName + ' ' + this.lastName;
};
}
});
While this is all good, I am not sure how this differs from directives.
What are the benefits of using components over traditional custom directives? And are components in Angular 1.5 and Angular 2 the same?
The .component DOES NOT replaces .directive like #rek Żelechowski said.
So..
There’s nothing you can do with .component() that you can’t do with .directive().
It aims to simplify the way we create “components” – which roughly means UI directives.
When can/should you use it?
Clearly there are a few cases where you can’t/shouldn’t use it:
If you need the link function (though you rarely should)
If you want a template-less directive, e.g. ng-click that doesn’t have a template or separate scope
For all your other directives, this should work. And because it saves on boilerplate and less error-prone it’s nicer to use.
Despite of all new goodies, .component() can’t fully replace .directive().
The .component is now preferred way of writing code because it favors good practices and gives developers ability to write code like in angular 2 (similar to Web Components). Basically, when you write code using component, upgrading to angular 2 will be easier. Functionalities remains almost the same. You should use .component always when it is possible.
Changes (extract)
component is declared using object instead of function
simplified isolated scope using binding property
components are always with isolated scope
some bad practices will not be possible
simpler, easier to understand configuration
lifecycle hooks: ($onInit(), $onChanges(changesObj), $doCheck(), $onDestroy(), $postLink())
Awesome article is here:
https://toddmotto.com/exploring-the-angular-1-5-component-method
When not to use Components (from docs):
for directives that need to perform actions in compile and pre-link functions, because they aren't available
when you need advanced directive definition options like priority, terminal, multi-element
when you want a directive that is triggered by an attribute or CSS class, rather than an element.
I believe, that the best description you can find is official guide: https://docs.angularjs.org/guide/component. It covers all changes, reasons for changes and gives you deep understanding of the components.
EDIT 01-2020:
I don't work on ng1 code anymore since at least a year
At the point of writing response (01-2017), impression that they are going to replace directives in most scenarios was correct. I removed a word "replaced" from the answer in 06-2017, because it is was indeed misleading at that point in time. However, since 1.5 you should still prefer components over directives when possible.
Actually, you should prefer not to use AngularJS at all. It is now in LTS and basically, only errors will be fixed. No new features. Also, LTS ends on 01-07-2021.
https://docs.angularjs.org/misc/version-support-status#long-term-support
PS. Using component instead of directive makes the code easier to port to ngx in the future.
Directives are NOT replaced, they just have been changed for lots of various reasons that might be a bit too much to get into here. The angular docs explain them pretty well, so you can start looking at the documentation there:
https://docs.angularjs.org/guide/component
To get a better idea of what the differences between directives and components are, I find that its better to reference the Angular 2.0 documentation. Angular 1.5 gave us a bridge to 2.0 that 1.4 and prior did not have. One of the bigger changes is removing $scope, another is providing Components as a way to build things (which is HIGHLY used in Angular 2.0).
All in all the very meat of the change is that it prepares the 1.X world to migrate to the 2.X world. In that world there are Components (which are element level directives at their heart), structural directives and attribute directives. See the below links to help understand each (along with the link provided above).
http://learnangular2.com/components/
https://angular.io/docs/ts/latest/guide/structural-directives.html
https://angular.io/docs/ts/latest/guide/attribute-directives.html

Categories

Resources