首页 > 解决方案 > 无法在角度 6 中设置未定义的属性“标题”

问题描述

为什么我收到此错误 无法设置未定义的属性“标题” 这里是我的代码 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'}];

  }

}

我正在尝试将值插入到我的变量中,那么如何解决这个问题?

标签: javascriptangular

解决方案


您需要先初始化typeOfProofObj变量,然后尝试访问它的属性。

@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'} ];    
  }

}

推荐阅读