gpt4 book ai didi

javascript - matInput 如何设置值

转载 作者:行者123 更新时间:2023-12-05 00:35:41 27 4
gpt4 key购买 nike

如何为 Angular Material 输入字段设置值。然后从我的组件中,我从我的数据库中获取数据作为 json 对象,我想将这些数据设置为 Angular Material 表单输入字段中的值。

this.http.get('http://localhost:8000/v1/passenger/2/getPassenger').
subscribe(
response => {
this.data = response.json();
}
);

如何在表单中传递值。

最佳答案

由于您使用的是表单输入,因此请使用 Angular 的 ReactiveForm。

进口 ReactiveFormsModule在您的 app.module.ts .

在您的组件中创建一个服务来保存您的表单组,例如:

@Injectable({
providedIn: 'root'
})
export class SettingsService {

public formGroup = new FormGroup({

name: new FormControl('', [

Validators.required,

])

});

}

现在在您的 api 调用中引用您的服务并更新值:
...
constructor(myformService: MyFormService) {}

yourApiCall() {

this.http.get('http://localhost:8000/v1/passenger/2/getPassenger')
.map(res => res.json())
.subscribe(
response => {
this.myformService.formGroup.controls.name.setValue(response.name);
});

}
...

并在您的组件中引用您的表单组:
<form [formGroup]="myformService.formGroup">

<mat-form-field>
<input matInput placeholder="Name" formControlName="name">
</mat-form-field>

</form>

有关更多信息,请参阅官方 Angular 文档: https://angular.io/guide/reactive-forms

关于javascript - matInput 如何设置值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48413036/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com