为什么我收到此错误 无法设置未定义的属性“标题” 这是我的代码 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'}];
}
}
我正在尝试将值插入变量中,那么如何解决此问题?
答案 0 :(得分:2)
您需要先初始化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'} ];
}
}
答案 1 :(得分:0)
您可以将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'}];
}
}
答案 2 :(得分:0)
另外,如果您对具有太多属性的变量有疑问,并且通过名称访问所有属性并不重要,则可以使用
typeOfProofObj : any = {}