我在TypeScript中定义了一个接口,如下所示:
export interface User {
id?: number;
name?: string;
logoUrl?: File;
emailUserName?: string;
emailPassword?: string;
}
使用User,我将其绑定到Angular html输入 . 如果我在输入中输入任何内容,则用户对象将包含值,但是,如果我不输入,则名称之类的属性将取消定义 . 如果我没有为name输入字符串,我怎么能得到名称的空值 . 更新
<div *ngIf="hero">
<h2>{{hero.name}} details!</h2>
<div>
<label>id: </label>{{hero.id}}</div>
<div>
<label>name: </label>
<input [(ngModel)]="hero.name" placeholder="name" />
<input [(ngModel)]="hero.location" placeholder="location" />
</div>
<button (click)="goBack()">Back</button>
</div>
//model
export class Hero {
private _location:string="test";
constructor(){
console.log(this._location);
this.location=this._location;
}
public id: number;
public name: string;
public location:string;
}
goBack(): void {
console.log(this.hero);
// this.hero=new Hero();
// console.log(this.hero);
//this.location.back();
}
}
如果我没有在输入中输入任何值,goBack将输出没有位置属性的英雄 .
3 回答
您可以为
User
而不是接口创建一个类,并在getter中执行以下操作:甚至在构造函数中为
this._name
分配一个空字符串 .如果您更喜欢使用界面,则可以使用以下功能:
编辑
是的,这是如何在ctor中设置默认值:
至于
get name()
部分,它是一个访问者,所以如果你使用它,那么:More on accessors .
你也可以使用这个简写:
你做不好吗?