Sonar displays an error stating "An assignment or function call was expected"

While working with NgRx, I came across the following error message:

'Expected an assignment or function call and instead saw an expression.'

I encountered a Sonar issue in my code snippet

this.sfForm.get('code')?.[this._mode ? 'disable' : 'enable']();
. I'm struggling to interpret this message from Sonar and figure out how to resolve it.

If anyone can help me understand the code better and assist in resolving the issue, that would be greatly appreciated.

<mat-form-field [formGroup]="sfForm">
  <input Input
         matInput
         (keydown.enter)="search($event.target.value)"
         [type]="''"
         formControlName="code"
         required>
</mat-form-field>
sfForm: FormGroup;
private _mode: boolean = true;
      
public set scanMode(value: boolean) {
  this._mode = value;
  this.sfForm.get('code')?.[this._mode ? 'disable' : 'enable']();
}

Answer №1

Here is a breakdown explaining the process:

this.sfForm.get('code') // retrieving value by key "code"
?.                      // if the value is `undefined` or `null`, stop here (refer to #1)
[                       // otherwise, accessing property using expression within [square brackets]
    this._mode ?        // checking if this._mode is truthy...
        'disable'       // setting the property to 'disable'
        : 'enable'      // setting the property to 'enable'
]                       // (see #2 below)
()                      // calling the function associated with that property (with 0 arguments)

If we were to describe the code in a more detailed manner, it would resemble something like this:

const code = this.sfForm.get('code')

if (code !== null && typeof code !== 'undefined') {
    let modeFunction

    if (this._mode) {
        modeFunction = code.disable
    } else {
        modeFunction = code.enable
    }

    modeFunction()
}

Answer №2

If you are looking to apply labels, the method you used will not allow you to assign values in this way.

object[field]

Instead, consider using a structure like this:

this.sfForm.get('code')?.[this._mode] = this.sfForm.get('code')?.[this._mode] ? 'disable' : 'enable'

Alternatively, if you prefer to store the field in a variable, you can do so in a more concise manner.

Keep in mind that when using '?' assigns, only statements can be utilized and functions cannot be called within them.

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

Tips for implementing md-icon in combination with md-autocomplete in Angular Material Design:

How can I include an md-icon in an md-autocomplete field? <md-autocomplete md-selected-item="ctrl.selectedItem" md-search-text-change="ctrl.searchTextChange(ctrl.searchText)" md-search-text="ctrl.searchText" md-items="it ...

Choosing Between Absolute and Relative Paths for Angular Component's 'templateUrls'

Could anyone assist me with resolving the issue I'm facing with 1 vs 2? 1) In my Angular project, I have implemented AoT for production. This necessitated changing my source code to utilize templateUrl and styleUrls that are relative to the component ...

Are there any potential performance implications to passing an anonymous function as a prop?

Is it true that both anonymous functions and normal functions are recreated on every render? Since components are functions, is it necessary to recreate all functions every time they are called? And does using a normal function offer any performance improv ...

Errors encountered while trying to install the ngx-admin template through npm

After cloning the ngx-admin angular template from the git repository located at https://github.com/akveo/ngx-admin, I encountered a series of errors when trying to install the node modules and run the project: npm ERR! code 1 npm ERR! path C:\Users&bs ...

What could be the reason for operators like tap and map not being invoked on the inner observable when combineLatest is used?

Can you clarify why the operators tap and map of inner observable are not being called? Shouldn't combineLatest subscribe to the observables it receives in obsArr? Why are these operators not triggered by this subscription? const obsArr = []; [[1, 2 ...

Caution: The absence of FIREBASE_CONFIG and GCLOUD_PROJECT environment variables may result in the failure to initialize firebase-admin

I followed a tutorial to set up the Firebase Admin SDK. https://firebase.google.com/docs/admin/setup I downloaded a JSON file (service account) from the Firebase console located at: C:\ct\functions\src\cargo-tender-firebase-adminsdk- ...

Discover the virtual scrolling feature in Angular's ng-select component

My web page is equipped with multiple dropdowns created using the *ngFor directive, allowing users to select multiple items from each dropdown. These dropdowns are implemented with ng-select for custom server-side search functionality. I am also intereste ...

Issue with prop type: MUI - experiencing a warning while using ReactJS with MUI?

Upon attempting to open the datepicker by clicking on the icon, I encounter the following warning. Here is the code snippet where the error occurs: const DatePickerTextField = React.forwardRef((props: TextFieldProps, ref) => { const theme = useTheme() ...

Sorting elements with a custom selector using Angular's ViewChild

Currently, I am delving into the realm of angular ViewChild. However, I find myself facing a roadblock when attempting to utilize ViewChild in selecting custom reference variables from the DOM. Within my template lie two tables: <mat-table #eventTable ...

The subcategory was not factored into my npm package

In my npm module 'ldap-pool', I'm facing an issue where the '@types/ldapjs' package, which is a dependency along with 'ldapjs', does not get installed when I add 'ldap-pool' to another project. This particular s ...

Tips for updating the barchart legend in an Angular application

Is there a way to switch the position of the legend from top to bottom in an nvd3 chart? https://i.sstatic.net/gWMFf.png options = { "chart": { "type": "multiBarChart", "height": 300, "margin": { "top": 20, "right": 20, "bottom": 45, ...

The 'initializeOnMount' property is a necessary requirement within the definition of the 'MoralisProviderInitializedProps' type

I encountered an unexpected issue with the code below: Type '{ children: Element; appId: string | undefined; serverUrl: string | undefined; }' is not compatible with type 'IntrinsicAttributes & MoralisProviderProps'. The property ...

Filtering in RxJS pipelines can be compared to an if-else statement

I'm not very familiar with JS and RxJS, so please pardon me if my question seems trivial. Here is a code snippet that I didn't write: prepare(): Observable<any> { const i = of({}).pipe( // Check if file type is image fil ...

The absence of a scroll bar on the web application is preventing me from scrolling properly

The vertical scroll bar on my Angular app seems to have disappeared mysteriously. I haven't made any changes to the code recently, and I'm struggling to figure out why it's missing. I've spent days trying to troubleshoot this issue with ...

Changing the size of a div component using Angular 6

Currently, I am working on implementing Angular's element resize feature. I am utilizing this library: https://github.com/mattlewis92/angular-resizable-element Here is my custom module: import { ResizableModule } from 'angular-resizable-elemen ...

Steps for reinstalling TypeScript

I had installed TypeScript through npm a while back Initially, it was working fine but turned out to be outdated Trying to upgrade it with npm ended up breaking everything. Is there any way to do a fresh installation? Here are the steps I took: Philip Sm ...

Retrieve the ultimate observable from a nested code block

Hey everyone, I'm having an issue with the code snippet below: return this.facebook.getFacebookUserInfos(req.token).pipe( switchMap(user => { return this._repo.findBy({email: user.email}).pipe( switchMap(foundUser = ...

One question I have is how I can successfully send a value within the RxJS subscribe function

I am currently in the process of transitioning the code to rxjs Here is my original code snippet. userAuth$: BehaviorSubject<ArticleInfoRes>; async loadArticleList(articleId: number) { try { const data = await this.articleApi.loadArticl ...

Query parameters in Angular 5 that have a global scope

Adding a global query parameter to every path of the application is my goal (such as /my/path?config=foo). I prefer not to use the option to preserve query params because I only want to retain this specific one. The application operates with various confi ...

Incorporating Common Types for Multiple Uses

Is there a way to efficiently store and reuse typings for multiple React components that share the same props? Consider the following: before: import * as React from 'react'; interface AnotherButtonProps { disabled?: boolean; onClick: (ev ...