Discover the unique value in Angular if it is not present in the list

I have a question about handling values in a list and displaying the "create value" component to the user when needed. How can I efficiently compare search input values with those in the list and determine if a match exists? If no match is found, the "create value" component should be shown.

.create-value(
    '*ngIf'='searchQuery && isValuesMode && ["Dropdown", "Multiselect"].includes(selectedFieldType) && !searchValues.length'
    '[ngClass]'='{"active":!searchValues.length}'
    '(click)'='onQuickCreateFieldValue($event)'
)
    .text CREATE VALUE
    info-item
        .custom-icon('[ngStyle]'="{'background-color': DEFAULT_COLOR}")
        info-item-text.in-dropdown('[text]'='searchQuery')
dynamic-list(
    '*ngIf'="!isValuesMode || ['Person', 'Dropdown', 'Multiselect'].includes(selectedFieldType)"
    '[mode]'='selectedFieldType === "Multiselect" ? "multi" : "single"'
    '[options]'='isValuesMode ? searchValues : fields | fieldOptions : searchQuery'
    '[searchQuery]'='searchQuery'
    '[keydownEvents$]'='keydownEvents$'
    '[ngStyle]'='{"height": isWithSearch ? "240px" : "280px"}'
    '[optionTemplateRef]'='isValuesMode ? optionTemplateValues : optionTemplateList'
    '(action)'='onAction($event)'
    '(closeList)'='closeList.emit()'
)
onSearch(query: string): void {
        if (!this.isValuesMode) {
            this.search.emit(query);
        } else {
            if (query) {
                switch (this.selectedFieldType) {
                case 'Person':
                    this.searchValues = this.values.filter(elem => {
                        const name = this.teamMap[elem.title].firstName + ' ' + this.teamMap[elem.title].lastName;

                        return name.toLowerCase().includes(query.toLowerCase());
                    });
                    break;
                case 'Dropdown':
                case 'Multiselect':
                    this.searchValues = this.values.filter(elem => elem.title.toLowerCase().includes(query.toLowerCase()));
                    break;
                }
                this.cdRef.markForCheck();
            } else {
                this.searchValues = this.values;
                this.cdRef.markForCheck();
            }
        }
        this.searchQuery = query;
    }

onQuickCreateFieldValue(event: MouseEvent): void {
    
        const newValue = {
            title: this.searchQuery,
            properties: [
                {
                    name: 'sequence',
                    value: this.selectedField.values.length.toString()
                },
                {
                    name: 'color',
                    value: this.DEFAULT_COLOR
                }
            ]
        };

        this.quickCreateFieldValue.emit({value: newValue, selectedField: this.selectedField, projectId: this.entity.projectId});
    }

Answer №1

I utilized the find method in this case. In the scenario where the search value does not exist in the array, I display the create-value component.

Here is the TypeScript code snippet:


            isSearchValueMode = false;
            
            if (this.values.find(elem => elem.title === this.searchQuery)){
                this.isSearchValueMode = false;
            }else{
                this.isSearchValueMode = true;
            }

And here is the corresponding HTML code:

.create-value(
    '*ngIf'='searchQuery && isValuesMode && ["Dropdown", "Multiselect"].includes(selectedFieldType) && isSearchValueMode'
    '[ngClass]'='{"active":!searchValues.length}'
    '(click)'='onQuickCreateFieldValue($event)'
)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can we import a CSS file selectively in Vue.js?

Can specific css-files be applied only when the current route has a "forAdmin" meta in my Vue.js project that includes both an admin-panel and client pages? ...

Preventing Multiple Form Submissions in JavaScript

I'm having an issue with my form submission to Parse where, after adding client-side validation, the data is being double submitted to the database. Despite adjusting my code based on other Stack posts and being new to JavaScript, I'm still expe ...

Encountering an ERROR during the compilation of ./src/polyfills.ts while running ng test - Angular 6. The module build

I encountered a problem in an angular project I am working on where the karma.config was missing. To resolve this, I manually added it and attempted to run the test using the command ng test. However, during the execution, an error message appeared: [./src ...

Using Ajax, transmit an array from javascript to a php function

How can I send an array from JavaScript to PHP using AJAX? I'm not sure how to do this, especially when trying to send it to a PHP function like a controller class. Can someone please correct me if I'm wrong? Below is my current JavaScript code f ...

how to load CSS and JS files on certain views in Laravel 5.2

Currently, I am facing a situation where I need to ensure that the CSS and JS files are loaded only on specific views in Laravel 5.2. Due to my boss's decision to eliminate RequireJS for loading JS files on our blade templates, we are now exploring a ...

What are the implications of using subresource integrity with images and other types of media

Subresource integrity is a fantastic method for securely using third-party controlled HTTP-served resources. However, the specification currently only covers the HTMLLinkElement and HTMLScriptElement interfaces: NOTE A future iteration of this spec may i ...

Resolve the type of the combineLatest outcome in RxJS

Encountering this scenario frequently in Angular when working with combineLatest to merge 2 observables that emit optional values. The basic structure is as follows: const ob1: Observable<Transaction[] | null>; const ob2: Observable<Price[] | nul ...

How can you turn consecutive if statements into asynchronous functions in JavaScript?

In my code, I have a loop with a series of if statements structured like this: for( var i = 0; i < results_list.length; i++){ find = await results_list[i]; //result 1 if (find.Process == "one") { await stored_proc(38, find.Num, find ...

Animating a Canvas to Follow Mouse Coordinates

I am looking for a way to animate a circle moving towards specific coordinates, similar to the game . I have attempted using the jquery animate() function, but it is too slow due to the constant updating of the target coordinates. Is there a faster metho ...

How to Retrieve the Value of <input type=date> Using TypeScript

I am currently developing a survey website and need assistance with retrieving user input for two specific dates: the start date and end date. I aim to make the survey accessible only between these dates, disabling the "take survey" button after the end da ...

"Embedding social content within an iframe may result in the element being unresponsive

I have a setup where I'm utilizing social embed to include Instagram content in the footer. When I insert the provided iframe code, the layout looks correct but the content is not clickable. <iframe src="https://embedsocial.com/facebook_album ...

The React client is unable to establish a connection with the server socket

Recently diving into the world of socket-io and react, utilizing express for the backend. The socket.io-client version being used is 3.0.3, while the backend's socket-io package matches at 3.0.3 as well. Interestingly enough, the server handles connec ...

:after pseudo-element along with HTML tags

I have recently designed a basic webpage in an attempt to simulate ajax using CSS. In order to achieve this, I aimed to create hidden radio buttons with visible labels, and load an external CSS file when the user clicks on a label. However, I encountered o ...

Change the http observable response to an array that can be used with ngFor

My goal is to dynamically load select options based on an API response, using observables in Angular 5 for HTTP requests. However, when trying to parse the response into select options, I encountered the following error: Cannot find a differ supporting o ...

Is there a way to include the request body (req.body) in the msg object using express-winston?

My current challenge involves logging {{ req.body }} using the msg: object in express-winston. Even after whitelisting the body with expressWinston.requestWhitelist.push('body');, it still does not appear in the log. export const accessLogger = ...

Methods for ensuring that fake browser tab focus remains on several tabs simultaneously

Is there a way to simulate multiple tab/window focus in a browser for testing purposes? I need to test pages that require user input and focus on active windows/tabs. Are there any different browsers, plugins, or JavaScript code that can help me achieve th ...

I need help differentiating "namespace" from "static attributes" in TypeScript

Separating namespace from static properties in TypeScript can sometimes be tricky. error: 'ClassA' only refers to a type, but is being used as a namespace here. class ClassA { static ClassB = class { }; } type T = ClassA // ok type T = C ...

Guidelines for callbacks and the impact on scope

I am currently diving into the world of scopes in angularjs, specifically when it involves calling callbacks on the module utilizing a directive. I have discovered three different methods to achieve the same goal and I am attempting to comprehend the advan ...

Tips for refreshing a React component using incremental changes retrieved from an API

I am developing a unique React application using Next.js and TypeScript, with an api-backed data set in one component that needs to be cached indefinitely. Unlike traditional examples I have found online, my component must: Fetch only the most recent 100 ...

Toggle a jQuery bar based on the presence of a specific CSS class

I am working on a feature where I can select and deselect images by clicking on a delete button. When an image is selected, a bar appears at the top. If I click the same delete button again, the image should be deselected and the bar should disappear. This ...