0
votes

why I am getting this error Cannot set property 'title' of undefined here is my code https://stackblitz.com/edit/angular-pkd3qr?file=src%2Fapp%2Fapp.component.ts

import { Component } from '@angular/core';


interface DropDownModel {
  displayName: string;
  value: string;
}

interface DropdownModelWithtitle {
  title: string;
  dropDownOptions: DropDownModel[];
}

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';
  typeOfProofObj: DropdownModelWithtitle;
  constructor(){
    this.typeOfProofObj.title = "ss";
    this.typeOfProofObj.dropDownOptions = [{displayName:'ss',value:'sss'}];

  }

}

I am trying to insert the value into my variable, so how to resolve this issue?

3

3 Answers

3
votes

You need to initialize typeOfProofObj variable first, then try to access it's properties.

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';
  typeOfProofObj: DropdownModelWithtitle = { title: null, dropDownOptions: null };

  constructor() {
     this.typeOfProofObj.title = "ss";
     this.typeOfProofObj.dropDownOptions = [ {displayName: 'ss', value: 'sss'} ];    
  }

}
0
votes

You could change DropdownModelWithTitle from interface to class, and set typeOfProofObj to new DropdownModelWithTitle()

interface DropDownModel {
  displayName: string;
  value: string;
 }

 class DropdownModelWithtitle {
  title: string;
  dropDownOptions: DropDownModel[];
 }

 @Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
  })
 export class AppComponent  {
   name = 'Angular';
   typeOfProofObj = new DropdownModelWithtitle();
   constructor(){
     this.typeOfProofObj.title = "ss";
     this.typeOfProofObj.dropDownOptions = [{displayName:'ss',value:'sss'}];

 }

}
0
votes

Also if you have a problem with a variable that has a too many properties and it's not important for you to access all of them by name, you can use

typeOfProofObj : any = {}