代码之家  ›  专栏  ›  技术社区  ›  user944513

无法在角度6中设置未定义的属性“title”

  •  0
  • user944513  · 技术社区  · 8 年前

    为什么我会犯这个错误 无法设置未定义的属性“title” 这是我的密码 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'}];
    
      }
    
    }
    

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

    2 回复  |  直到 8 年前
        1
  •  2
  •   Suren Srapyan    8 年前

    您需要初始化 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'} ];    
      }
    
    }
    
        2
  •  0
  •   Nenad Radak    8 年前

    您可以将DropDownModelWithTitle从接口更改为类, 并将typeofProofObj设置为新的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'}];
    
     }
    
    }