我一直在努力解决 Ionic Angular 中表单的一些问题。 我有一个组件,它基本上是一个由输入(组件)填充的表单。
问题是,表格似乎是在数据到达输入字段之前就被填写的。 该数据来自在父组件中注入的服务。 我想显示来自服务的数据而不是组件中的对象。来自服务的数据是“Jack”,但它显示我“John”。
谢谢!
HTML 组件
<form [formGroup]="myForm">
<ion-item button="true" detail="false">
<ion-input label="Name"
formControlName="userName"
placeholder="Enter Name"></ion-input>
</ion-item>
</form>
组件:
export class EventoComponent implements OnInit {
@Input() users: Atencion[] = [{
userName: 'John'
}];
public myForm: FormGroup = this.fb.group({
userName: [this.users[0].userName]
})
constructor(private fb: FormBuilder) {}
}
父亲组件:
export class EventoPage implements OnInit {
users: Atencion[] = [];
constructor(private dataService: GetDataService) {}
ngOnInit() {
this.dataService.getUsersData()
.subscribe( users => {
this.users.push(users);
});
}
}
我正在尝试使用之前由服务填写的输入来填写表单
在输入中使用设置器。
public myForm!:FormGroup
public users:Atencion[] //<--see if really you need
@Input('users') set _users(value:Atencion[]){
this.users=value;
this.myForm= this.fb.group({
userName: [value[0].userName]
});
}
或者,在setter中使用setValue
users: Atencion[] = [{
userName: 'John'
}];
public myForm: FormGroup = this.fb.group({
userName: [this.users[0].userName]
})
@Input('users') set _users(value:Atencion[]){
this.users=value;
this.myForm.controls.userName.setValue(value[0].userName)
});
}