JavaScript & Angular (Week 4 with Ashley's help)
What is a callback function?
Any function that is passed as a parameter and later called by another function.
Angular: package-lock.json
Contains the full details of every library you are using. You may also change dependencies here.
What did ECMA script 6 bring us?
-Lexical scoped variables -Access modifiers -Classes
Variable scopes in JS
1) Global, declared outside of any function 2) Block scope, inside of any if/if-else/switch statements or do/do-while loops 3) Lexical scope, allows for local scope inside of block
What does 'exporting' your class in Angular do?
1) It allows us to provide a classname to identify it by, as well as define any constructors or lifecycle hooks. Example: export class AppComponent{ title = 'Mafia Web Page!'; }
What is a decorator (@)?
1) Provide metadata for Angular to understand the purpose of the file at hand. 2) Can be used to define files as components, or even expose elements to parent components.
How do you reference objects or elements not specific to the one you are using?
1) You import them into app.module.ts with: import {ClassName} from 'location/of/class'; EXAMPLE: import {NgModule} from '@angular/core'; import {AppComponent} from './app.component'; 2) AND add them to the imports
How can I manipulate the DOM
1) document.createElement 2) .replaceChild 3) parent.removeChild 4) .innerHTML = ''; many more as well these are just a few
What are some different events?
1) onchange - An HTML element has been changed. 2) onclick - The user clicks an HTML element 3) onmouseover - The user moves the mouse over an HTML element 4) onmouseout - The user moves the mouse away from an HTML element 5) onkeydown - The user pushes a keyboard key 6) onload - The browser has finished loading the page
Datatypes in JS
1) string 2) number (16 digits you start losing accuracy) 3) boolean 4) null 5) undefined 6) object
What are issues of prototypal inheritance?
1) tight coupling problem 2) fragile base class problem 3) inflexible hierachy problem (all evolving hierarchies are wrong for new uses 4) duplication by necessity 5) Gorilla/banana problem (What you wanted was a banana, but what you got was a gorilla holding the banana, and the entire jungle) *Prototypes are not classes.*
Var vs Let vs Const
1) x - means global scope 2) var x - functional scope 3) let x - Lexical scope or block scope dies when block ends 4) const x - an ummutable, lexical scoped variable
What are some JavaScript Errors?
1. EvalError An error has occurred in the eval() function 2. RangeError A number "out of range" has occurred 3. ReferenceError An illegal reference has occurred 4. SyntaxError A syntax error has occurred 5.TypeError A type error has occurred 6.URIError An error in encodeURI() has occurred *look a graph error occurrence frequency*
Dynamic tables: HTML portion (Mafia example)
HTML: <h3>Dynamic Tables!</h3> <ul style="list-style-type:none"> <li>First Name</li> <li><input type="text" id=fname></li> <li>Last Name</li> <li><input type="text" id=lname></li> <li>Family Name</li> <li><input type="text" id=family></li> <li><button onclick="addMafia()">ADD MAFIA</button></li> </ul> <table border="2px" onmouseover="changeSection()" id="theTable"> <tr> <th colspan=3>MAFIA TABLE!</th> </tr> <tr> <th>MAFIA ID</th> <th>FIRST NAME</th> <th>LAST NAME</th> <th>FAMILY</th> </tr> </table>
Angular: angular.json
Allows you to root config a project as a whole.
Self invoking functions
(function inVoke(){ console.log("Called."); })();
What does a module component expect?
*1) Declarations:* Any components being used must be declared in the module before use. *2) Imports:* Used for bringing in other modules for use. 3) *Providers:* Used for setting up "services" with aim to provide streams of data for use throughout the application. 4) *Bootstrap:* Declare which components will be wrapped as the root component of the application.
AJAX
*Asynchronous JavaScript & XML (AJAX).* - A framework offered by the browser that leverages JS. Allows for asynchronous calls to a server. - We start the call, and once it is finished are brought back via a call-back function. - AJAX is not a programming language.
Bubbling vs Capturing
*Bubbling* innermost element to outer elements. *Capturing* outermost element to the inner elements.
What are some ways of One-way binding in Angular?
*Component to View:* *1)Interpolation binding:* - in the View template enclosed with {{}} 2) *Property binding:* - used to bind values of the component/model properties to the HTML element with the [property] = 'expression' 3) *Style binding:* - able to set inline styles to the HTML element [style.font-size.px]="50" 4) *Class binding:* able to add and remove CSS class names from the HTML elements, similar to attribute binding but it starts with the prefix class, optionally followed by a '.' and the name of the class [class.txtright]='true' 5) *Attribute binding:* able to set the value of the attribute directly [attr.colspan] = "2" *View to Component:* - *Event binding:* binds the data from an HTML element to a component <button (click)='onClick()'>Click me</button>
Objects in JS Syntax
*Defined with an object literal:* var person = {firstName: "Geralt", lastName: "of Rivia",} *They may have methods stored in function definitions:* fullName: function() { return this.firstName + " " this.lastName; Note: if you access a method without the (), it will return the function defintion.
What is different between AngularJS and angular 4+?
*JavaScript & TypeScript:* AngularJS is based on JavaScript while Angular is based on TypeScript which is a superset of javascript. *Scope & Component:* Angular.JS uses scope and controller for variables while Angular uses components and has no term like scope and controller. I am sure there are more...anyone else care to add? Let me know :)
JSON
*JavaScript Object Notation (JSON)* A minimal, readable format for structuring data. It is used primarily to transmit data between a server and web application *What is it used for?* - Only used to store data *Why is it a favorite among developers?* - Because of 2 methods: 1) JSON.parse(), Converts a string representation of a JavaScript object and converts into the the actual object in question. 2) JSON.stringify(), which converts a JavaScript object into a String that other languages can parse through.
Null vs Undefined
*Null* An empty or non-existent value. Null is assigned, and explicitly means nothing. *VS* *Undefined* A variable has been declared, but the value of that variable has not yet been defined.
Promises vs Observables
*Promise* - A type of object where a user sends data we guarantee that we will be getting something back. We don't know what, and we don't know when but we will be getting something. - Can only listen to one event at a time. - Once a promise starts getting data, you cannot interrupt it without breaking it. (NOT GOOD) *VS.* *Observables* - Can listen to multiple events at once - You can stop an observable at any point in time once it starts streaming data. - Arrow notation is used to handle it.
Using Http Rest with Angular
*Representational State Transfer (REST)* is an architectural style that defines a set of constraints to be used for creating web services. Web services that conform to the REST architectural style, or RESTFUL web services provide interoperability between computer systems on the Internet. A good resource on this: https://www.metaltoad.com/blog/angular-5-making-api-calls-httpclient-service
The five XHR states
*State 0:* Request is not configured yet, but the xhr object is created: - new XMLHttpRequest object created, but not configured *State 1* Request has been properly configured: - We called the .open() method to configure the xhr. *State 2* The request has been sent to the server -We called the .send() method of xhr *State 3* Request is received and being processed -Communication with the server has been established successfully -Yet we have not received a response yet. State 4 Request has been sent, and proper response has been received. -request/response lifecycle is finished.
Asynchronous vs Synchronous
*Synchronous:* executions are sequential. - In web apps, this means it performs an action and it waits for the result before the next action may be performed. *Asynchronous:* While an action is awaiting a result, you can perform other actions and eventually circle back to the completed asynchronous action.
What are pipes?
*What are they?* - A convenient and reusable way to transform data within a template. i.e. formatting dates, formatting currencies, filtering and ordering a list, etc. *How do I use them?* 1) Add the "|" character and the name of the pipe you want to use after an angular template expression. 2) Similar to using directives you will need to specify which pipes are available to this component.
What are the three declaration statements and what are they used for? Which part of the file is this located in?
*What are they?* - selector: 'app-root', - templateUrl: './app.component.html', - styleUrls: ['./app.component.css'] *What are they used for?* 1) Selector is used to define the identifying element 2) templateUrl links the component to the html that will be injected 3) links the component to a custom CSS for it *Where are the located?* They are located in app.component.ts
Angular Interpolation
*What does it do?* - Displays a component property by binding the property name *How is it used?* - With interpolation, you put the property name in the view template, enclosed in double curly braces as such: {{myHero}}.
What is PROMPT in JS?
*What does it do?* - You can use the "prompt()" function to take user input. *What are the parameters?* - The function has one parameter which will be the question the user is prompted with. - The user will input their answer, and the answer is returned from the prompt function. <button onclick="document.getElementById('p').innerHTML = 'Your name is: ' + prompt('What is your name?')"> </button> <p id="p">INSERT YOUR NAME</p>
Classes in Angular
*What does it do?* A class in Angular interacts with the view through an API of properties and methods. An example: export class DirectivesComponent implements OnInit { visible: boolean = true; buttonText:string = "HIDE ANSWER" newMafia: Mafia = new Mafia("","",""); mafias:Mafia[] = [ new Mafia("Bobbert", "Bobson", "Bobson"), new Mafia("Tim", "Timson", "Bobson"), new Mafia("Edgar", "Edgarson ", "Smith") ];
What is a template literal?
*What is is?* - They are string literals allowing embedded expressions. *How can they be used?* You can use multi-line strings and string interpolation features with them. *What is the syntax of it?* Template literals are enclosed by the back-tick (' ') character instead of double or single quotes and can contain placeholders. The expressions in the palceholders and the text between them get passed to a function. Example: 'string text ${expression} string text' (Note: the above ' is supposed to be a back-tick not a single quote.)
Angular
*What is it?* - A TypeScript-based open-source front-end web application framework mainly maintained by Google. *How is it used?* Pairs with Node.js to create a front and back-end structural framework for building dynamic web apps. *Why is it useful?* It lets you use HTML as your template language and implements features such as data binding and dependency injection.
What is databinding?
*What is it?* Databinding is the act of passing data from the backend to the view or vice versa. *How is it used?* - Databinding where the data is either passed from the backend to the front end *OR* front end to the back end only. (Where data is simultaneously passed both forward and backward in one go, this is called two-way data binding, a relic of AngularJS.)
Event Binding
*What is it?* Event binding is the view to component approach to one-way databinding in which we take user input or an event from the front end and transfer it to the backend. *How do we do it?* This is done within the element's tag where we use parenthesis instead of brackets. We will typically wrap these around actual events as well.
EventListener
*What is it?* Functions that react when a certain event/action is performed. *What parameters do they take?* They take 3 parameters: 1) The action to be listened for 2) The function to be called, or rather the definition of the function. This is called a 'callback function'. 3) 'useCapture' a boolean that is falsey by default if you don't include it. If you want to use capturing versus bubbling, you need to pass 'true'. d1.addEventListener("click", click1, true);
What is property binding?
*What is it?* Property binding is a one way data binding technique that binds from the back to the front, but this time we apply it WITHIN element tags. *How do we do it?* We do this by surrounding what would be the 'attribute' of the element with square brackets [likeThis]. <div [hidden]=visibility> <p>I am not hidden!</p>
Angular components
*What is it?* The fundamental building blocks of Angular apps. *What are they used for?* 1) Display data on the screen 2) Listen for user input 3) Take action based on that input.
Components in Angular
*What is it?* The fundamental building blocks of Angular apps. *What are they used for?* 1) Display data on the screen 2) Listen for user input 3) Take action based on that input.
Two-way Event Binding
*What is it?* We can set up two way databinding, where data we input is fed back to a component and can be brought back all in the same action. *What do we do it?* In order to do this, we need to invoke both property and event binding alongside a 'directive' called ngModel. (remember to import it in appModule and add it to imports section) <div> <input type="text [(ngModel)]="userInput"> <p>You have inputted: {{userInput}}</p> </div>
What is interpolation in depth?
*What is needed?* In order to perform interpolation you need to write the item to be evaluated in between double curly braces. For example: 2 + 5 = {{2 + 5}} *What is it?* It is essentially a block of typescript as innerHTML. (A downside is that you cannot perform string interpolation with an element's tag. ([Like an attribute]) *What else can it be used for?* We also use interpolation to pull data from component.ts files directly. As such, the component's "variable" variable evaluates to: {{variable}}
Routing in Angular
*What its it?* - Routing is a feature that Angular uses to achieve true Single page format (SPA). *What does it do?* - Routing is where we set up pages to be injected through the url that we are connected to . - The urls themselves do not point to the separate files to be displayed due to the fact that then that would be a multi page application.
Angular Directive
*What they are:* - Extended HTML attributes with the ng-prefix. *How do we use them and what do they do?* - A way we can invoke Angular functionality within a html file. - They act as syntax that can be used in html format without breaking the front end.
bundling and webpack
*ng Build* - Invokes webpack (a bundler) and takes all components, services, and classes that are detailed by our modules and bundles them together in a distributable folder
What is the different between '==' and '==='?
- *'=='* tests for loose equality and preforms type coercion. - This means we compare two values after converting them to a common type. *VS* *'==='* tests for strict equality between two values. Both the type and the value you're comparing have to be exactly the same.
Publisher/subscriber design
- A messaging pattern where senders of messages, called publishers, do not program the messages to be sent directly to specific receivers, called subscribers, but instead categorize published messages into classes without knowledge of which subscribers, if any, there may be. - Similarly, subscribers express interest in one or more classes and only receive messages that are of interest, without knowledge of which publishers, if any, there are. (This is a broad description) Example of usage: http.get('friends.json').map(response => response .json()).subscribe(result => this.result =result);
What is the Event object?
- All event objects in the DOM are based on the Event Object. - Therefore, all other event objects (like MouseEvent and KeyboardEvent) has access to the Event Object's properties and methods. *Look at image*
What is JavaScript?
- An interpreted client side language - A Runtime language - Supported by most browsers - NOT Java! - Interpreted by most browsers - Weakly typed language.
TypeScript
- An open-source programming language developed and maintained by Microsoft. - It is a strict syntactical superset of Javascript - Adds optional static typing to the language. - It transcompiles to JavaScript. - One of the big benefits is to enable IDEs to provide a richer environment for spotting common errors as you type the code.
Caching in Angular
- Angular uses caching to allow us to use the back/forward buttons on our browser to navigate properly. - It is only one page, but Angular will leverage implicit bookmarks to keep track of different pages and use the back and forward buttons.
What does the asterisk(*) mean in front of ngIF/ngFor?
- Any directive that has an asterisk means that it is a structural directive. - This means that the directive in question will acutally manipualte the html directly. - Will be capable of physically deleting or adding HTML on the spot for us.
What is the JSON syntax?
- Data is in name/value pairs - Data is separated by commas - Curly braces hold objects - Square brackets hold arrays
HttpClient
- HttpClient offers a simplified client HTTP API for Angular applications that rests on the XMLHttpRequest interface exposed by browsers. - Additional benefits of HttpClient include testability features, typed request and response objects, request and response interception, Observable apis, and streamlined error handling.
What is a prototype in JS?
- JS has only one construct: objects. - Each object has a private property which holds a link to another object called its prototype
What is Prototypal Inheritance?
- JavaScript only has one construct: objects. - Each object has a private property which holds a link to another object called its prototype. - That prototype object has a prototype of its own, and so on until an object is reached with null as its prototype. - By definition, null has no prototype, and acts as the final link in this prototype chain. - ALL this is represents the idea of prototypal inheritance
What is linting?
- Linting is the process of running a program that will analyze code for potential errors.
What is MVC?
- MVC Pattern stands for Model-View-Controller Pattern. - This pattern is used to separate application's concerns. *Model* - Model represents an object or JAVA POJO carrying data. It can also have logic to update controller if its data changes. *View* - View represents the visualization of the data that model contains. (HTML) *Controller* - Controller acts on both model and view. It controls the data flow into model object and updates the view whenever data changes. It keeps view and model separate
Typescript Class with Array (example syntax)
export class AppComponent { title = 'Tour of Heroes'; heroes = ['Windstorm', 'Bombasto', 'Magneta', 'Tornado']; myHero = this.heroes[0]; } *This will select Windstorm... whoever that is.*
Describe which scopes a new object has access to in the following pseudocode:
function coolBeans() { var java; var coffee; return { get java; get coffee; }}
Dynamic tables: JS portion (Mafia example)
let mafiaId = -1; function addMafia(){ //Store the user input let mafiaFName = document.getElementById("fname").value; let mafiaLName = document.getElementById("lname").value; let familyName = document.getElementById("family").value; //Create nodes for storing the text values let mId = document.createTextNode(++mafiaId); let fNameText = document.createTextNode(mafiaFName); let lNameText = document.createTextNode(mafiaLName); let familyText = document.createTextNode(familyName); let del = document.createTextNode("X"); //With text nodes created, we need to place them in element nodes. let td1 = document.createElement('td'); //<td></td> let td2 = document.createElement('td'); //<td></td> let td3 = document.createElement('td'); //<td></td> let td4 = document.createElement('td'); //<td></td> let td5 = document.createElement('td'); //<td></td> let delBut = document.createElement('button'); //<button></button> delBut.setAttribute("onclick", "remove(" + mafiaId + ")"); //<button onclick="remove(someID)"></button> delBut.setAttribute("style", "color:red"); //<button style="color:red" onclick="remove(someID)"></button> delBut.appendChild(del); //<button style="color:red" onclick="remove(someID)">X</button> td1.appendChild(mId); td2.appendChild(fNameText); td3.appendChild(lNameText); td4.appendChild(familyText); td5.appendChild(delBut); let row = document.createElement('tr'); row.appendChild(td1); row.appendChild(td2); row.appendChild(td3); row.appendChild(td4); row.appendChild(td5); row.setAttribute("id", mafiaId); document.getElementById("theTable").appendChild(row); document.getElementById("fname").value = ""; document.getElementById("lname").value = ""; document.getElementById("family").value = ""; }
Functions in JS Syntax
r = "things" function foo(){ console.log("function"); if (true) { lex = "luthor"; console.log("block"); console.log(r); console.log("lex = " + lex); } things = "stuff"; var things2 = "stuff2"; var z = "pizazzz"; console.log(z); } Bonus: describe the different variable scopes
What is truthy vs falsy?
JavaScript has a set of values that may evaluate to true or false but may not equal true or false. Because of this, we call these values truthy and falsy.
What does the event.stopPropagation(); do in JS?
Known as event canceling, it will prevent nested actions from executing past a certain point: function click1(){ window.alert("D1"); } function click2(){ window.alert("D2"); event.stopPropagation(); } function click3(){ window.alert("D3"); }
What is a closure in JS?
A closure is an inner function that has access to the outer (enclosing) function's variables scope chain.
Angular: README.md
A convenient spot to keep notes on the application.
What is a lifecycle hook?
A lifecycle hook is a method that gets called at key points during the lifecycle of the component should you want extra vision on the initializing points.
What is a module?
A module is a collection of components, services, directives, that are bundled together as a separate piece of application that can be plugged or removed from a main application without issue.
Dependency Injection
Dependency Injection (DI) is a powerful pattern for managing code dependencies. Dependency Injection consists of three things. 1) Injector 2.) Provider 3.) Dependency Injector : The injector object use to create instances of dependencies. Provider : A provider is help to injector for create an instance of a dependency. A provider takes a token and maps that to a factory function that creates an object. Dependency : A dependency is the type of which an object should be created.
Angular: tslint.json
Determines how Angular will syntactically parse your document and see if it is correct.
DOM
Document Object Model, determines the logical structure of a webpage. It is typically represented as a 'tree' structure.
What does it mean to be a weakly typed language?
Means it has no problem mixing unrelated types in the same expression without explicitly changing types. Example: a=10; b="a"; c=a.b; print c; 10a
Types of listeners in JS
Mouse events: -mouseenter/mouseleave -mousedown/mouseup -mouseover -click -dblclick -select Keyboard events: -keydown -keypress -keyup Form events: -reset -submit Resource events: -cached -error -load Network events: -online -offline (A comprehensive list: https://developer.mozilla.org/en-US/docs/Web/Events)
Can TypeScript enforce datatypes?
Sure can!
What must you include when you access the object outside of the class?
The *this* keyword followed by the object.
In angular, what is a convenient shortcut for creating getters/setters?
Setting the constructor to public...duh!
Angular: styles.css
The CSS that is applied application wide.
What is the app.component.ts file used for?
The component's class code written in TypeScript
What is the app.component..css file used for?
The component's private CSS styles
What is the app.component.html file used for?
The component's template, written in HTML
*ngFor
The ngFor structual directive is used to access each item in the list: In the template: <h1>{{title}}</h1> <h2>My favorite hero is: {{myHero}}</h2> <p>Heroes:</p> <ul> <li *ngFor="let hero of heroes"> {{ hero }} </li> </ul>s
What is an object prototype in JS?
The object instance from which the object instance is inherited.
What is ECMA Script?
The scripting language specification that JavaScript is based on.
@Injectable
This declarator tells angular that this service is expecting/allowing other services to be injected into it. Make sure you execute your injectable either way.
What is variable hoisting?
Variables are hoisted to the top of the function/statement. It is useful because you can refer to variables declared later in the code.
What is type coercion?
When the data type of a value is changed IMPLICITLY during mixed value typed expressions
Angular: tsconfig.json
Where the app will save bundled files. Similar to the target folder in Maven.
Angular: src
Where the project details are.
AJAX: XML HttpRequest
XMLHttpRequest (xhr) is the object we use in AJAX in order to: 1) Communicate with a server API endpoint 2) To send a request 3) Get a response with the data we wanted.
XMLHttpRequest
XMLHttpRequest (xhr) object is the object we use in AJAX in order to: 1) Communicate with a server API endpoint 2) To send a request 3) Get a response with the data we wanted.
What is the difference between a = 5, and var a = 5?
a = 5 can be used for global scope VS var a = 5 will be used for functional scope
Arrays in JS Syntax
var Universe = ['stars', 'planets', 'some dust', 'ectoplasm']