Angular - Set value only if property is present

Check if the 'rowData' property exists and assign a value. Can we approach it like this?

if(this.tableObj.hasOwnProperty('rowData')) {
  this.tableObj.rowData = this.defVal.rowData;
}

I encountered an error when attempting this, specifically inside the if statement.

Property 'rowData' does not exist on type '{}'.

UPDATE:

@Input() tableObj: {};
defVal: {
    rowData: [1,2,3]
};
 
ngOnInit() {
}
 
reset() {
    if( this.tableObj.rowData !== undefined) {
        this.tableObj.rowData = this.defVal.rowData;
    }
}

Error message while building:

error TS2339: Property 'rowData' does not exist on type 'never'.

Answer №1

To prevent the issue from occurring, consider implementing the following code within your if statement.

     if(this.tableObj && this.tableObj.rowData !== undefined){  
      this.tableObj.rowData = this.defVal.rowData;
      }

Answer №2

Absolutely, there are several ways to achieve this:

if ('rowData' in this.tableObj) {

}

Alternatively,

if (this.tableObj.rowData) {

}

And of course, the method you mentioned:

if (this.tableObj.hasOwnProperty('rowData')) {

}

In my opinion, I prefer the first approach as it is more self-explanatory and enhances readability.

UPDATE:

If I may inquire further about your intention, the rowData appears to be an array. Are you attempting to ascertain if a specific item exists within the array as an object property?

To retrieve a specific item from the array, you must specify the index like so:

rowData[0]

The value at index 0 represents the first element in the array. To access subsequent elements, you would use rowData[1], and so on.

Hence, your code snippet should resemble the following:

if (this.tableObj[this.rowData[0]] !== undefined) {
        this.tableObj[this.rowData[0]] = this.defVal.rowData;
}

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

"Error in Visual Studio: Identical global identifier found in Typescript code

I'm in the process of setting up a visual studio solution using angular 2. Initially, I'm creating the basic program outlined in this tutorial: https://angular.io/docs/ts/latest/guide/setup.html These are the three TS files that have been genera ...

Is it compatible to use Typescript version 2.4.2 with Ionic version 3.8.0?

Is it compatible to use Typescript 2.4.2 with Ionic 3.8.0? $ ionic info cli packages: (C:***\AppData\Roaming\npm\node_modules) @ionic/cli-utils : 1.18.0 ionic (Ionic CLI) : 3.18.0 global packages: cordova (Cordova CLI) : not insta ...

The Angular2 component link imported in the core.module is not functioning properly

Adhering to the guidelines provided in the Angular style guide found at https://angular.io/styleguide#!#04-11, I have created a simple navigation setup. My app.component contains links like <a routerLink="hello">hello</a>, which work perfectly ...

Tips for simulating behavior in express using Typescript and the Mocha library

Help with mocking 'Request' in Mocha using express with Typescript needed! Here is the current approach: describe("Authorization middleware", () => { it("Fails when no authorization header", () => { const req = { ...

Angular date picker component

What could be the reason for the bsDatePicker container in angular 10 appearing empty? Browser HTML http://prntscr.com/zvhi7g <bs-datepicker-container role="dialog" aria-label="calendar" class="bottom ng-tns-c104-1 ng-star-ins ...

Narrow down your search results with date range filtering in Angular Material

Seeking guidance as a newcomer to Angular Material, I am trying to implement a date range filter for a table of N results. The options in the filter select are (1 day, 5 days, 1 week, 15 days), which are populated using a variable JS vm.rangos=[ {id ...

Encountering unspecified values when subscribing to a BehaviorSubject and receiving it as an Observable

My goal is to display the name of the currently logged-in user in the header of my application. However, I encountered an issue where upon refreshing the page, the value would be lost due to SPA behavior (even though the data is stored in local storage). T ...

Getting started with installing Bootstrap for your Next.Js Typescript application

I have been trying to set up Bootstrap for a Next.js Typescript app, but I'm having trouble figuring out the proper installation process. This is my first time using Bootstrap with Typescript and I could use some guidance. I've come across these ...

Which is the better choice for simply invoking a service method - subscribe or toPromise?

When implementing the search method below, I simply assign the value of BehaviourSubject in the service. However, I am unsure whether it is possible to execute this operation without using either subscribe() or toPromise() after the .pipe() block in the ...

Having trouble with Angular router.navigate not functioning properly with route guard while already being on a component?

I am currently troubleshooting an issue with the router.navigate(['']) code that is not redirecting the user to the login component as expected. Instead of navigating to the login component, I find myself stuck on the home component. Upon adding ...

Enhance your FullCalendar experience with React by displaying extra information on your calendar

I am new to using React and FullCalendar, and I have a page layout similar to the image linked below. https://i.sstatic.net/MooTR.png Additionally, I have a list of events structured as shown: id: "9", eventId: "1", ...

Converting a text file to JSON in TypeScript

I am currently working with a file that looks like this: id,code,name 1,PRT,Print 2,RFSH,Refresh 3,DEL,Delete My task is to reformat the file as shown below: [ {"id":1,"code":"PRT","name":"Print"}, {" ...

Issues with loading image assets on GitHub Pages after deploying in production with Angular2, Angular-cli, and Webpack

This is NOT a repeated query: This particular issue presents the problem, but it pertains to a project not built with angular-cli like mine does, hence a webpack.config file is absent. While my described dilemma involves accurately configuring the base_u ...

Angular2 is experiencing an unresolved peer dependency issue with ng2-bootstrap

While attempting to install ng2-bootstrap using npm, I encountered the following errors and warnings: https://i.stack.imgur.com/K7XjC.png Any suggestions on how to resolve this issue? ...

The latest version of npm Boostrap (4.1.0) is missing some important CSS properties for the `background` tag

I am currently working on an Angular 5.2.10 project that utilizes angular-cli and bootstrap version: 4.0.0-beta.2 with a specific css class called .en-icon-24: .en-icon-24 { background: url(../../../../assets/img/icons.png) -370px 0px; width: 24 ...

Flag is activated to retrieve the data from the @Input source

@Input() config= []; flag = false; I need to change the flag to true only when I receive data in the config from the @input. Where should I do this? The data in the config is delayed and I am unable to access it in ngOnInit but can get it in ngOnChanges. ...

Typescript with Angular: Despite having 7 values in the map, Map.get is returning undefined

Why does Map.get always return undefined when using a number from a form element (extra1) in this code snippet? extraById = new Map<number,Extra>(); @Input() extra1: number = -1; formChanged(carConfigurationFormChanged : any) { const index ...

When I receive a 404 response from the API, I aim to start my observable

How can I trigger my observable initialization when receiving a 404 response from the API? The code snippet below is not working as expected. const urlParams = { email: this.email }; this.voicesProfileObservable$ = this.service.request<any>( AVAI ...

The API request does not provide randomized results and does not show any display

I am facing an issue with a button that is supposed to fetch a random user from an API. When I retrieve all the users, the information is displayed correctly. However, when I try to select a user at random, it does not work as expected. Also, it seems to a ...

Expanding the typings for an established component in DefinitelyTyped

Is there a way to define new typings for additional props in DefinitelyTyped? After updating the material-ui library with some new props for the SelectField component, I realized that the typings in DefinitelyTyped are outdated. Is it possible to extend th ...