4 回答
TA贡献1891条经验 获得超3个赞
你定义了一个类型,但它的值仍然是undefined
import { Component, OnInit } from '@angular/core';
export class User {
constructor(
public firstname: string,
public lastname: string,
public age: number,
public email: string,
) { }
}
@Component({
selector: 'app-user',
templateUrl: './user.component.html',
styleUrls: ['./user.component.css'],
})
export class UserComponent {
user: User;
// Another option
// user = new User('Muhammad', 'Shaeel', 23, 'shaeel678@gmail.com');
constructor() {
this.user = new User('Muhammad', 'Shaeel', 23, 'shaeel678@gmail.com');
}
}
Stackblitz示例
TA贡献1834条经验 获得超8个赞
这对我有用
export class UserComponent {
user = {
firstname: '',
lastname: '',
age: 0,
email: ''
};
TA贡献1815条经验 获得超13个赞
如果您只是想user在内部包含对象UserComponent而不为其声明单独的类,您也可以这样做:
import { Component } from '@angular/core';
@Component({
selector: 'app-user',
templateUrl: './user.component.html',
styleUrls: ['./user.component.css']
})
export class UserComponent {
user = {
firstname: "",
lastname: "",
age: -1,
email: ""
};
constructor() {
this.user.firstname = 'Muhammad';
this.user.lastname = 'Shaeel';
this.user.age = 23;
this.user.email = 'shaeel678@gmail.com';
}
}
TA贡献1829条经验 获得超4个赞
用户对象为空,
试试下面
import { Component, OnInit } from '@angular/core';
export interface IUser: {
firstname: string;
lastname: string;
age: number;
email: string;
};
@Component({
selector: 'app-user',
templateUrl: './user.component.html',
styleUrls: ['./user.component.css'],
})
export class UserComponent {
user: IUser = {
firstname: '',
lastname: '',
age: null,
email: ''
};
constructor() {
this.user.firstname = 'Muhammad';
this.user.lastname = 'Shaeel';
this.user.age = 23;
this.user.email = 'shaeel678@gmail.com';
}
}
添加回答
举报