这是我的模型类,我试图在我的组件中设置值但是我收到的错误是“无法设置未定义的属性'年龄'”....
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);
}
}
答案 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:""};