我希望用户可以编辑他的数据。我使该页面可访问数据。它存储在 information
我希望用户在进入 View 时已经看到他的数据,例如他的用户名或他的电子邮件,并且他还可以编辑或删除该字符串。我首先尝试使用占位符,但这不是实际输入。我还尝试在我的表单中初始化数据,但这也不起作用。
这是我试过的。
页面.html
...
<ion-item class="input-item">
<ion-label color="secondary" position="floating">Username</ion-label>
<ion-input type="text" formControlName="username" required></ion-input>
</ion-item>
...
页面.ts
ngOnInit() {
if (this.authService.authenticationState) {
this.storage.get(USER_ID).then(val => {
this.id = val;
console.log(this.id);
this.userService.getUserDetails(this.id).subscribe(result => {
this.information = result;
console.log(this.information);
});
});
}
this.updateUserForm = new FormGroup({
username: new FormControl('', Validators.required),
email: new FormControl('', Validators.compose([
Validators.required,
Validators.pattern('^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$')
])),
birthdate: new FormControl(Validators.required),
gender: new FormControl(this.genders[0], Validators.required),
});
}
最佳答案
一种方法(在如下定义 FormGroup
时初始化字段:
this.updateUserForm = new FormGroup({
username: new FormControl(this.information ? information.username : "", Validators.required),
email: new FormControl(this.information ? information.email : "",, Validators.compose([
Validators.required,
Validators.pattern('^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$')
])),
birthdate: new FormControl(Validators.required),
gender: new FormControl(this.genders[0], Validators.required),
});
更新
如果数据是异步提供的,使用 FormControl.setValue()
函数如下:
updateUserForm: FormGroup;
ngOnInit() {
if (this.authService.authenticationState) {
this.storage.get(USER_ID).then(val => {
this.id = val;
this.userService.getUserDetails(this.id).subscribe(result => {
this.updateUserForm.get("username").setValue(result.username)
this.updateUserForm.get("email").setValue(result.email)
// If result value corrspond with updateUserForm fileds' names use:
// this.updateUserForm.setValue(result)
});
});
}
this.updateUserForm = new FormGroup({
username: new FormControl('', Validators.required),
email: new FormControl('', Validators.compose([
Validators.required,
Validators.pattern('^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$')
])),
birthdate: new FormControl(Validators.required),
gender: new FormControl(this.genders[0], Validators.required),
});
}
关于javascript - 如何在输入中初始化用户可编辑的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58845027/