Accessing specific array element in an Angular2 Template - javascript

I have an array that I can loop through using ng-for syntax. However, ultimately I want to access just a single element of that array. I cannot figure out how to do that.
In my component script I have
export class TableComponent {
elements: IElement[];
}
In my template, I am able to loop through the elements via
<ul>
<li *ngFor='let element of elements'>{{element.name}}</li>
</ul>
However, trying to access an item in the element array by secifically referencing an item utilizing
x {{elements[0].name}}x
does not seem to work.
The formatting in the template is pretty explicit, so I want to be able to access each element of the array explicitly in the template.
I am not understanding something basic....

2020 Edit :
{{elements?.[0].name}}
is the new way for the null check
Original answer :
{{elements[0].name}}
should just work. If you load elements async (from a server or similar) then Angular fails when it tries to update the binding before the response from the server arrived (which is usually the case). You should get an error message in the browser console though.
Try instead
{{elements && elements[0].name}}

Work around, use ngIf check the length. elements? means if elements is null, don't read the length property.
<div *ngIf="elements?.length">
{{elements[0].name}}
</div>

Related

Javascript document.querySelector just need the value

my webpage excerpt looks like this
<div class="current-timestamp" style="--duration:"00:13:19"; --absolute-position:"00:00:00";"><span class="position"></span><span class="divider"></span><span class="duration"></span></div>
i try to get the value 00:13:19 via the chrome console with this command
document.querySelector(".current-timestamp");
however i receive the full code like above.
What do i need to do to just receive "00:13:19" ?
It's not common to store the value of a component in a CSS variable like you have done, however it can be accessed in the following way:
getComputedStyle(document.querySelector(".current-timestamp")).getPropertyValue("--duration");
Essentially, we are getting the computed style of the element in question, and then using getPropertyValue to get the value of the duration variable on the element.
However, I would highly advise against using CSS variables for storing non-style related values in the future.
Edit: This can actually be done using the style property directly, as this is set on the element itself:
document.querySelector(".current-timestamp").style.getPropertyValue("--duration");

Unable to create ref dynamically in Vue.js

I am rendering a list and then a sublist within that. I want to have a ref to my inner list which will be named something like list-{id}. However, I am not able to achieve this.
Here is the code snippet:
<ul class="scrollable-list" ref="getScrollableRef(company.id)">
<li v-for="operation in getOperations(company.id)">
{{company.name}}
</li>
</ul>
When I inspect the $refs object:
$vm0.$refs
Object {getScrollableRef(company.id): Array(13)}
I think for some reason the value is not being evaluated. Has anyone faced this?
Edit: I am trying to solve this problem https://github.com/egoist/vue-mugen-scroll/issues/14
In your example, you are specifying that the ref should literally be named "getSchoolableRef(componany.id)". That's why the $refs object contains an getScrollableRef(company.id) property with an array of 13 elements as its value.
If you want to use the result of the getSchoolableRef method as the name of the ref, you can use v-bind or the shorthand colon:
<ul class="scrollable-list" :ref="getScrollableRef(company.id)">
As you mentioned, $refs is not reactive and changing the bound value once the component has initialized will not update the property name in $refs. But, you can dynamically set the name of the ref when the component initializes.

What does this code using [].filter.call do?

I’m learning javascript and trying to write code that sorts a list, removing elements if they meet certain criteria.
I found this snippet that seems promising but don't have a clue how it works so I can adapt it to my needs:
list = document.getElementById("raffles-list").children; // Get a list of all open raffles on page
list = [].filter.call(list, function(j) {
if (j.getAttribute("style") === "") {
return true;
} else {
return false;
}
});
Can you guys help me learn by explaining what this code block does?
It's getting all the children of the "raffles-list" element, then returning a filtered list of those that contain an empty "style" attribute.
The first line is pretty self-evident - it just retrieves the children from the element with id "raffles-list".
The second line is a little more complicated; it's taking advantage of two things: that [], which is an empty array, is really just an object with various methods/properties on it, and that the logic on the right hand side of the equals sign needs to be evaluated before "list" gets the new value.
Uses a blank array in order to call the "filter" method
Tells the filter to use list as the array to filter, and uses function(j) to do the filtering, where j is the item in the list being tested
If the item has a style attribute that is empty, i.e. has no style applied, it returns true.
Edit:
As per OP comment, [].filter is a prototype, so essentially an object which has various properties just like everything else. In this case filter is a method - see here. Normally you just specify an anonymous function/method that does the testing, however the author here has used the .call in order to specify an arbitrary object to do the testing on. It appears this is already built into the standard filter method, so I don't know why they did it this way.
Array like objects are some of javascript objects which are similar to arrays but with differences for example they don't implement array prototypes. If you want to achieve benefits of array over them (for example like question filter children of an element )you can do it this way:
Array.prototype.functionName.call(arrayLikeObject, [arg1, [arg2 ...]]);
Here in question array like is html element collection; and it takes items without any styling.
list is assigned a collection of elements that are children of the raffles-list element
list is then reassigned by filtering its elements as follows
an empty array is filtered by calling it with the parameter list and a callback function. The formal parameters for call are this (which is the list) and optionally further objects (in this case a callback function)
The callback function receives a formal parameter j and is called for each element
If the element's value for the style attribute is empty the element is retained in the array. Otherwise it is discarded.
At the end list should contain all elements that don't have a value for its style attribute

Why can I not map keys onto React component

my render looks like this:
<ul>{liElements}</ul>
the liElements is an array of <li>word</li> created with a for-of loop.
(for the sake of argument, I do not have access to the function that creates that array)
I'm understanding the value of keys, however they are not valuable in this situation as none of the component's values will be changing, Especially since in absence of a key, "react takes the array position as key" anyway, Perfect! I want that, why does it insist on sending me a error message letting me know they are necessary, I know it doesn't know they're not necessary, be it also doesn't know they are necessary, so how bout a yellow warning?
I know I can ignore it, but it is very annoying to always have the message log to console, (especially since this message could useful elsewhere)
react.js:19287 Warning: Each child in an array or iterator should have a unique "key" prop
So since I can do
liElements[0].key // null
I thought I can just do
liElements.map(function(a,i){a.key=i;});
<ul>{liElements}</ul>
alas;
bundle.js:39123 Uncaught TypeError: Cannot assign to read only property 'key' of object '#<Object>'
Why is it readOnly? Is there anyway I can assign these totally unnecessary keys after I receive the array just so the error message stops showing?
Lets say you have a list of items you want to be li's
let items = ['item 1', 'item 2', 'item 3', 'item 4', 'item 5']
let elems = items.map( (item, index) => { return <li key={index}>{item}</li> }
You want to map your list and as you do specify a key. Why do this? because you are rendering a tree into the DOM and for React to know which exact element you are going to try and manipulate you need to pass a specific key. This way you can do things like onClick handlers.. and stuff like that.
Additionallly React uses these specific keys for performance in rendering. so even if you think its unnecessary and the end result is identical when not passing a key. It still is REALLY important, because React wont have to generate a key for every item every single render.
Finally when you go to render it.
return (
<ul>
{elems}
</ul>
)
Edit
To what Dave was saying in the comments.. Keys are created on object creation aka React.createElement(...). After their creation they are immutable. Again this is because you are creating a tree.. if you try to manually change a key then the whole tree structure would have to be 're-keyd' which is a bad idea (this is why it is read only). The key is an internal thing that react uses, but when you render dynamic elements you need to specify the key so there is no duplication of keys.
Edit 2
Heres some helpful links for you
Another Answer I Gave Regarding Keys
React Dynamic Children Documentation
Importance of Keys - Example
Dynamic elements with examples of wrong ways to do it
If you're trying to set keys, I believe you have to set them in the li elements themselves like this:
<li key={index}>list item</li>

Why no error when accessing a DOM element that doesn't exist?

I have some divs with partial views in them. Why would a reference to a div that doesn't exist not show some kind of error? For example, I only have one taskN div right now:
<div id="task1">
#Html.Partial("~/Views/PartialViews/TaskDosCommand.cshtml")
</div>
This is my jQuery to show the div:
$('#task' + task.PrestoTaskType).show();
When task.PrestoTaskType is 1, the task1 div correctly displays. However, when task.PrestoTaskType is anything but 1, like 2, then nothing displays (which is good), but there is no error; no error shows on the web page, and nothing displays in the Chrome developer tools console:
Shouldn't some kind of error display when accessing a DOM element that doesn't exist?
No, because what jQuery does is .show() all elements that the jQuery object wraps. If that's no elements at all, then so be it.
That's precisely a monad-like aspect of jQuery that makes it so useful: imagine the code you 'd have to write if things didn't work that way:
var $whatever = $(...);
if ($whatever.length) $.doSomething();
This is simply worse: you need to introduce a variable (in order to avoid waste) and a conditional... for what gain exactly?
If you want to see what jQuery matched you can do that very easily with .length as above, perhaps also using .filter in the process.
One of the nice things about jQuery is that all jQuery elements return a collection, whether that is 0, 1, or many elements. This is convenient because you don't need to check the size of the collection or wrap it in an array yourself when you want to call methods on it (each for example doesn't break for 0-1 elements).
While what you're talking about is frustrating in this particular case, it is better for jQuery to work this way so you don't have to do those sorts of checks everywhere else.
If you want to branch code based on the existence of such an element, you can do this:
var task = $('#task' + task.PrestoTaskType);
if (task[0]) {
task.show();
} else {
// task not found
// take appropriate steps
}
The [0] accessor will return the first DOM element in the jQuery object or undefined if the jQuery object is empty. Since your jQuery object was constructed with an ID selector, it either contains exactly one DOM element or it's empty.

Categories