【问题标题】:How to bind data to a mat form field in angular?如何将数据绑定到角度的垫子表单字段?
【发布时间】:2021-07-23 06:05:52
【问题描述】:

我有一个提取该数据的 http 请求,并且我正在 UI 上填充该数据。现在,当用户单击编辑时,将显示一个表单。单击编辑按钮时,我们如何在字段上分配和显示值?因为我想使用该数据提交。电子邮件、名字等应显示在该字段上。

当我单击编辑时,表单字段的值应该是 getuserdetails 中的值,例如 firstname 、 lastname 等,例如 {{this.data.emailAddress}} 下面的示例,但我希望它是输入字段的值

#初始化

ngOnInit(): void {
    this._activatedRoute.queryParams.subscribe((params) => {
      this.userId = params.id;
      this.getUserGeneralDetails();
    });
  }

#构造函数

 constructor(
    private _activatedRoute: ActivatedRoute,
    private _notificationService: NotificationService,
    private _userProfileService: UserProfileService,
    private _router: Router,
    private fb: FormBuilder
  ) {
    this.generalForm.disable();
    this.securityForm.disable();
  }

我只想在点击编辑时在表单域上显示数据。

 generalForm = new FormGroup({
    email: new FormControl(),
    fname: new FormControl(),
    lname: new FormControl(),
    phone: new FormControl(),
    companyName: new FormControl(),
    title: new FormControl(),
  });

刚接触 Angular 的人非常想了解技术和想法。谢谢。


#模板

 <div class="card" #generalCard>
            <span class="anchor" id="general"></span>
            <div class="card-header">
                <mat-icon class="card-icon">group</mat-icon>
                <div class="title">GENERAL</div>
                <div class="spacer"></div>
                <button mat-button *ngIf="generalForm.disabled" (click)="generalForm.enable()">
                    <mat-icon>edit</mat-icon> Edit
                </button>
                <button mat-button *ngIf="generalForm.enabled" (click)="generalForm.disable()">
                    Cancel
                </button>
                <button mat-stroked-button *ngIf="generalForm.enabled" (click)="saveGeneralFormChanges()">
                    Save Changes
                </button>
            </div>
            <div class="card-content" *ngIf="generalForm.disabled" >
                <div class="line-item">
                    <div class="title">EMAIL</div>
                    <div class="detail">{{this.data.emailAddress}}</div>
                    <mat-icon class="active" style="color:#00B0DB;">check_circle</mat-icon>
                </div>

                <div class="line-item">
                    <div class="title">EMAIL</div>
                    <div class="detail">{{this.data.emailAddress}}</div>
                    <mat-icon>check_circle_outline</mat-icon>
                    <button mat-button class="detail active">Resend welcome email</button>
                </div>

                <div class="line-item">
                    <div class="title">FIRST NAME</div>
                    <div class="detail">{{this.data.firstName}}</div>
                </div>

                <div class="line-item">
                    <div class="title">LAST NAME</div>
                    <div class="detail">{{this.data.lastName}}</div>
                </div>

                <div class="line-item">
                    <div class="title">PHONE NUMBER</div>
                    <div class="detail">+1 {{this.data.phoneNumber}}</div>
                </div>

                <div class="line-item">
                    <div class="title">COMPANY NAME</div>
                    <div class="detail">{{this.data.companyName || 'None'}}</div>
                </div>

                <div class="line-item">
                    <div class="title">TITLE</div>
                    <div class="detail">{{this.data.title || 'None'}}</div>
                </div>
            </div>

#GetUserData

getUserGeneralDetails() {
    this.isInProgress = true;
    this._userProfileService
      .getUserGeneralDetails(this.userId)
      .pipe(finalize(() => (this.isInProgress = false)))
      .subscribe({
        next: (res) => {
          if (res.isSuccess) {
            this.data = res.data;
          }
        },
        error: (err) => this._notificationService.showError(err),
        complete: noop,
      });
  }

#字段代码

<div class="card-content" *ngIf="generalForm.enabled">
                <form [formGroup]="generalForm" class="generalForm">
                    <mat-form-field appearance="fill" class="email">
                        <mat-label>Email</mat-label>
                        <input matInput formControlName="email" />
                    </mat-form-field>
                    <button mat-raised-button class="validateEmail">Validate email</button>
                    <mat-divider></mat-divider>
                    <mat-form-field appearance="fill" class="fname">
                        <mat-label>First Name</mat-label>
                        <input matInput formControlName="fname" />
                    </mat-form-field>
                    <mat-form-field appearance="fill" class="lname">
                        <mat-label>Last Name</mat-label>
                        <input matInput formControlName="lname" />
                    </mat-form-field>
                    <mat-form-field appearance="fill" class="phone">
                        <mat-label>Phone Number</mat-label>
                        <input matInput formControlName="phone" />
                    </mat-form-field>
                    <mat-form-field appearance="fill" class="companyName">
                        <mat-label>Company Name</mat-label>
                        <input matInput formControlName="companyName" />
                    </mat-form-field>
                    <mat-form-field appearance="fill" class="title">
                        <mat-label>Title</mat-label>
                        <input matInput formControlName="title" />
                    </mat-form-field>
                </form>
            </div>
        </div>

【问题讨论】:

  • 在这种情况下(数据输入表单),我将使用 Angular 响应式表单来完成任务。见angular.io/guide/reactive-forms
  • 我在Sir上方添加了一个表单控件
  • 您必须遵循响应式表单文档,我不适合将其复制到答案中:)

标签: javascript angular typescript templates


【解决方案1】:

您的 HTML 代码看起来不错,根据您的问题,您在将数据填充到表单控件时遇到了问题。可以这样做:

constructor(private fb: FormBuilder) { }

fillUpData() {
     this.generalForm = this.fb.group({
         email: [this.data.email, [Validators.required]],
         fname: [this.data.fname, [Validators.required]],
         lname: [this.data.lname, [Validators.required]],
         phone: this.data.phone,
         companyName: this.data.companyName,
         title: this.data.title
    });
}

您需要在获得数据后调用此方法。所以在你的 API 调用之后。

getUserGeneralDetails() {
    this.isInProgress = true;
    this._userProfileService
      .getUserGeneralDetails(this.userId)
      .pipe(finalize(() => (this.isInProgress = false)))
      .subscribe({
        next: (res) => {
          if (res.isSuccess) {
            this.data = res.data;   // After this call function.
            this.fillUpData();
          }
        },
        error: (err) => this._notificationService.showError(err),
        complete: noop,
      });
  }

执行此操作后,如果您收到与表单组相关的错误,则在您的 HTML 代码中添加 *ngIf="generalForm" 之类的条件...这意味着如果表单存在则呈现其 formControl...

【讨论】:

  • 先生,如果仅单击“编辑”按钮,我只想显示 matform 字段和表单,但现在每次加载页面时都会显示,我已经更新了上面的代码。谢谢
  • 您可以创建一个局部变量来检测其是否为editMode。单击编辑按钮时只需设置editMode = true,否则在仅显示值时设置为false。
猜你喜欢
  • 1970-01-01
  • 2011-08-02
  • 1970-01-01
  • 1970-01-01
  • 2016-01-06
  • 1970-01-01
  • 2018-08-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多