Is it possible to achieve the following in HTML using Angular 2+?
{{ object.array.map((o) => o.property ) }}
Whenever I try to execute this code, it crashes the Angular application. Do I need to utilize Pipes or any other technique?
Is it possible to achieve the following in HTML using Angular 2+?
{{ object.array.map((o) => o.property ) }}
Whenever I try to execute this code, it crashes the Angular application. Do I need to utilize Pipes or any other technique?
In Angular expressions, defining functions is not allowed. Instead, you can use pipes which are specifically optimized for the templates and can be reused across various components.
<pre>{{ object.array | pluck:"property" | json }}</pre>
By using a pluck pipe:
@Pipe({name: 'pluck'})
export class PluckPipe implements PipeTransform {
transform (input: any[], key: string): any {
return input.map(value => value[key]);
}
}
It is advised not to call functions in the component to compute values for the template. Instead, it's better to perform such operations in ngOnInit()
or ngOnChanges()
if data needs to be mutated.
Pipes offer purity, meaning they are only executed when the incoming data is mutated. When you invoke a function like {{doWork(object.array)}}
, Angular assumes it's not pure and executes it with every change detection.
Updated:
When working with Arrays in Angular, it's recommended to treat them as immutable. Creating a new instance of the Array when modifications are needed is preferred. For instance; items = [...items, newItem];
rather than items.push(newItems)
.
This approach helps in resolving change detection issues related to pipes, ngFor, OnPush change detection, and state stores.
https://medium.com/dailyjs/the-state-of-immutability-169d2cd11310
One option is to come up with alternative solutions to make it work, but in my opinion, it is best to avoid using function calls in templates as they can have a negative impact on performance. The same goes for impure pipes, which would be required for this method to be dependable.
Instead, consider the following approach:
mappedArray = [];
ngOnInit() {
this.mappedArray = object.array.map( (o)=> o.property );
}
{{ mappedArray }}
This method is cleaner, more reliable, easier to read and modify, and easier to understand. It also provides more control over when your functions are evaluated.
One way to accomplish this is by creating a get property and using it in the following manner:
element
info = [
{type : 'x'},
{type : 'y'},
{type : 'z'},
]
get types () {
return this.info.map( (i)=> i.type )
}
layout
{{types | json}}
If you have a component, you can include a function like this:
customFunction(array: any[]){
return array.map(item => item.property);
}
Then in your html template, assuming array
is already defined, you can easily call the function wherever you need the array. For example:
<div *ngFor="let item of customFunction(array)>
{{item.property}}
</div>
It's important to note that you can't directly execute code in the html template without using functions.
*It's also important to mention that this approach may not be optimized as the customFunction()
will be repeatedly called in the template.
I have recently embarked on learning TypeScript and encountered a confusing behavior. Upon encountering this error: Type 'ComponentClass<{}>' is not assignable to type 'StatelessComponent<void | RouteComponentProps<any>> ...
I'm currently utilizing the jsTimezoneDetect script to identify the user's current timezone. The code below shows the result as America/Chicago. Is there a way to display CDT/CST instead (based on today's date)? var timezone = jstz.determin ...
Just implemented a simple navigation using react-router-dom. Managed to get it working with this.props.history.push('/pathName'); But I'm not entirely sure if my understanding and approach are correct. Any advice on correcting my mistakes wo ...
I am working with dynamically created input fields const [data, setData] = useState({ native: [{}], rolls: [{}] }) // initial data {navtive?.map((item, index) => { return ( <input type="text" name={item.id} ...
Is there a way to remove text from my canvas element without losing the background image of the canvas? I'm considering saving the Image source and reapplying it to the Canvas Element after using clearRect, but I'm unsure how to execute this sol ...
My Vue application is utilizing vue-router and vuex. I acquire an authentication token from my API, store it in localStorage, and then push it to the store. However, when the page refreshes, the app is unable to retrieve the token from localStorage and the ...
I am working on a popover component that appears below a textfield component. The goal is to trigger a menu when the user types a specific key, like :, into the textfield. The user can then select an option from this menu to autocomplete the textfield. A ...
Issue Overview: I have noticed that the rectAreaLight behaves differently compared to other light helpers in my project. Despite using the "useHelper" function and placing it in the "three/examples" folder, the position of the rectAreaLight does not change ...
Looking at the code below, it essentially fades all the images to 70% within the contact class. When an image is hovered over, its opacity changes to 100%. If multiple images are hovered over or multiple hover events occur in succession, the events will st ...
Let me show you exactly what I mean by setting up a demo Nuxt blog at https://example.com/nuxtblog/. This demonstration includes articles populated by the @nuxt/content package. The website has been generated statically using the nuxt generate command. Fol ...
Trying to solve the challenge of creating a fullscreen slider similar to the one described in this question, I created a jsfiddle (currently on hold) Despite knowing that scrolling too fast causes bugs and that scrolling both ways has the same effect, m ...
Hey, I'm trying to eliminate thumbnail images from YouTube. The code I am currently using is: while (true) { $("ytd-thumbnail").remove() } As of now, when I input this code in the console, it successfully removes all thumbnail images. However, I ...
When I click on the first option in the dropdown menu, it does not display the selected option in the field. However, when I select the second option, then the value of the first option appears, and when I choose the third option, the value of the second o ...
I need some assistance in fetching specific JSON object data. Specifically, I am looking to extract the name, poster image URL, size of the second backdrop image, and version number. As a newcomer to JSON, I was wondering if there is an easy way for me to ...
In our dataset, we have a specific table that contains valuable information. My main objective is to transfer an argument extracted from parsed JSON data to a separate JavaScript function known as newStory(value['stories']) using the onclick meth ...
So, I'm working on a jQuery code snippet that controls the visibility of a rectangle element: $("#rectangle").hide(); $("#toggle-rec").click(function () { $("#rectangle").toggle(2000); }); This code hides the rectangle initially and toggles it ...
How can I infer the props of the first child element and enforce them in TypeScript? I've been struggling with generics and haven't been able to get the type inference to work. I want to securely pass component props from a wrapper to the first ...
I spent hours troubleshooting a unit test for my Vue.js component, but no matter how much I searched the internet, I kept encountering this error: console.error node_modules/vue/dist/vue.runtime.common.dev.js:1884 TypeError: Cannot read property ' ...
Here is a simple example of jsdom code using the script parameter. Despite my best efforts to reference external JS files, I keep running into this issue: ReferenceError: exVar is not defined Does anyone know what might be causing this problem and how ...
A situation arose where I needed to lazy load a popups module outside of the regular router lazy-loading. In order to achieve this, I made the following adjustments: angular.json "architect": { "build": { ... "options": { ... "lazyM ...