【问题标题】:How set value for matInputmatInput 如何设置值
【发布时间】:2018-07-02 22:34:51
【问题描述】:

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

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

如何在表单中传递值。

【问题讨论】:

  • 你的意思是,你能帮我写PHP吗?

标签: javascript angular-material angular2-forms


【解决方案1】:

乍一看,您似乎忘记将响应映射到 json...

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

此时,您的“数据”变量将拥有您想要的 json.. 然后在您的模板上,您可以采用几种不同的角度方式。这是一个简单的方式

<mat-form-field *ngFor="let user of data">
    <input matInput placeholder="Name" [(ngModel)]="user.name">
</mat-form-field>

更新: 为此,您必须将 rxjs 模块添加到您的项目中...

npm install --save rxjs

并将其导入您的 *.component.ts 文件

import 'rxjs/add/operator/map';

您可能还必须添加 Observable,否则它可能也可以工作

import { Observable } from 'rxjs';

【讨论】:

  • ManageComponent_Host.ngfactory.js? [sm]:1 ERROR TypeError: this.http.get(...).map 不是函数
  • 你必须 npm install --save rxjs 并导入它的地图..编辑答案
  • 我得到了答案,很佩服您对我的问题的回答。
  • core.js:1440 ERROR TypeError: response.json is not a function 为什么现在会出现这种错误
  • 不。 ngModel 在 Angular 6+ 中被弃用。不是解决方案。
【解决方案2】:

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

在您的app.module.ts 中导入ReactiveFormsModule

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

@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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-19
    • 1970-01-01
    • 1970-01-01
    • 2019-01-01
    • 2019-10-06
    • 2021-07-01
    • 2021-02-10
    • 2012-07-26
    相关资源
    最近更新 更多