无法设置未定义的属性'age'

时间:2017-02-25 16:13:11

标签: angular

这是我的模型类,我试图在我的组件中设置值但是我收到的错误是“无法设置未定义的属性'年龄'”....

frst.model.ts

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


    export interface mydata
    {
    name :string;
    age:string;
    data: string;
    }

FSRT-Component.ts

import { Component,Output,Input,OnInit, } from '@angular/core';
import { mydata } from './frst.model';
@Component({
  selector: 'my-Component',
  template: `
  <div><h1>hello</h1></div>
  `,
})
export class MyComponent  {
 @Input() nputmydata:mydata;
 @Output() outputmydata:mydata;
 PassData:mydata;

 constructor()
 {
    this.PassData.age='my name';
    this.PassData.data ='hello';
    this.PassData.name='rajeev';
    this._senddata(this.PassData);
 }



 private _senddata(PassData:mydata)
 {

console.log(PassData);

 }
}

1 个答案:

答案 0 :(得分:2)

1)将PassData字段初始化为空对象或创建具有该类型的类。

PassData:any = {};

2)如果你想进行类型检查,可以使接口参数可选,如

 export interface mydata
    {
    name?:string;
    age?:string;
    data?: string;
    }

PassData:mydata = {};

3)如果你想要严格的typechecking初始化具有空字符串值的对象,

PassData:mydata = {name:"", age: "", data:""};