繁体   English   中英

angular材料的表格控制问题

[英]Form control problem with angular Material

当我想编辑我的用户时,我的控制台中会出现此消息。

我在 web 上看到了一些解决方案,有些人对此有问题,但对我没有解决方案。

有人有同样的问题吗?

EditUserDialogComponent.html:37 ERROR Error: 
      ngModel cannot be used to register form controls with a parent formGroup directive.  Try using
      formGroup's partner directive "formControlName" instead.  Example:


    <div [formGroup]="myGroup">
      <input formControlName="firstName">
    </div>

    In your class:

    this.myGroup = new FormGroup({
       firstName: new FormControl()
    });

      Or, if you'd like to avoid registering this form control, indicate that it's standalone in ngModelOptions:

      Example:


    <div [formGroup]="myGroup">
       <input formControlName="firstName">
       <input [(ngModel)]="showMoreControls" [ngModelOptions]="{standalone: true}">
    </div>

    at Function.modelParentException (forms.js:6182)
    at NgModel._checkParentType (forms.js:6754)
    at NgModel._checkForErrors (forms.js:6740)
    at NgModel.ngOnChanges (forms.js:6640)
    at checkAndUpdateDirectiveInline (core.js:31905)
    at checkAndUpdateNodeInline (core.js:44366)
    at checkAndUpdateNode (core.js:44305)
    at debugCheckAndUpdateNode (core.js:45327)
    at debugCheckDirectivesFn (core.js:45270)
    at Object.eval [as updateDirectives] (EditUserDialogComponent.html:42)

这是我的 HTML,

我认为是表单控件的问题,但是如果我按照错误消息的说明进行操作,我也有同样的...

<div class="manage-content">
  <div class="title">
    <mat-icon class="user-icon">how_to_reg</mat-icon>
    <h3>Edit a user</h3>
  </div>
  <form [formGroup]="form" (ngSubmit)="onSubmit()">
    <mat-form-field class="full-width-input">
      <input id="firstName" matInput placeholder="First name" formControlName="f_name" [(ngModel)]="selectedUser.f_name"#f_name>
      <mat-error *ngIf="isFieldInvalid('f_name')">
        The first name you've entered is malformed.
      </mat-error>
    </mat-form-field>
    <mat-form-field class="full-width-input">
      <input id="middleName" matInput placeholder="Middle name" formControlName="m_name" [(ngModel)]="selectedUser.m_name" #m_name>
      <mat-error *ngIf="isFieldInvalid('m_name')">
        The middle name you've entered is malformed.
      </mat-error>
    </mat-form-field>
    <mat-form-field class="full-width-input">
      <input id="lastName" matInput placeholder="Last name" formControlName="l_name" [(ngModel)]="selectedUser.l_name" #l_name>
      <mat-error *ngIf="isFieldInvalid('l_name')">
        The last name you've entered is malformed.
      </mat-error>
    </mat-form-field>
    <mat-form-field class="full-width-input">
      <input id="email" matInput placeholder="Email" formControlName="email" [(ngModel)]="selectedUser.email" #email>
      <mat-error *ngIf="isFieldInvalid('email')">
        The email you've entered is malformed.
      </mat-error>
    </mat-form-field>
    <mat-form-field class="full-width-input">
      <div class="visibility">
        <input id="password" matInput type="password" placeholder="Password" formControlName="password" [(ngModel)]="selectedUser.password">
        <mat-icon *ngIf="isPasswordVisible" (click)=showPassword()>visibility</mat-icon>
        <mat-icon *ngIf="!isPasswordVisible" (click)="showPassword()">visibility_off</mat-icon>
      </div>
      <mat-error *ngIf="isFieldInvalid('password')">
        The password you've entered is malformed.
      </mat-error>
    </mat-form-field>
    <mat-form-field>
      <mat-select placeholder="Role" class="full-width-input" [(ngModel)]="selectedUser.role">
        <mat-option value="option">End-User</mat-option>
        <mat-option value="option">View-User</mat-option>
        <mat-option value="option">Vendor</mat-option>
        <mat-option value="option">Tool Guy</mat-option>
      </mat-select>
    </mat-form-field>
    <div class="cta-btn">
      <button mat-raised-button class="createUserBtn" color="primary" type="submit">Update user</button>
      <button mat-raised-button class="createUserBtn" color="warn" type="submit" (click)="click()">Cancel</button>
    </div>
  </form>
</div>

@Component({
  selector: 'app-edit-user-dialog',
  templateUrl: 'edit-user-dialog.component.html',
  styleUrls: ['./manage-user.component.scss']
})
export class EditUserDialogComponent {
  form: FormGroup;
  formSubmitAttempt: boolean;
  isPasswordVisible = false;
  selectedUser: User;

  constructor(private formBuilder: FormBuilder, private userService: UserService, public dialog: MatDialog, public dialogRef: MatDialogRef<EditUserDialogComponent>,
              @Inject(MAT_DIALOG_DATA) public data: any) {
    this.selectedUser = data;
    console.log(this.selectedUser);
    this.form = this.formBuilder.group({
      email: ['', Validators.compose([Validators.required, Validators.pattern('^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$')])],
      password: ['', Validators.compose([Validators.required, Validators.minLength(10), Validators.maxLength(35)])],
      f_name: ['', Validators.compose([Validators.required, Validators.maxLength(100)])],
      m_name: ['', Validators.compose([Validators.maxLength(100), Validators.pattern('[0-9]+')])],
      l_name: ['', Validators.compose([Validators.required, Validators.maxLength(100)])]
      // client: ['', Validators.compose([Validators.required, Validators.minLength(10), Validators.maxLength(35)])],
    });
  }

  click(): void {
    this.dialogRef.close();
  }

  showPassword() {
    const pass: HTMLInputElement = document.getElementById('password') as HTMLInputElement;
    if (pass.type === "password") {
      this.isPasswordVisible = true;
      pass.type = "text";
    } else {
      this.isPasswordVisible = false;
      pass.type = "password";
    }
  }

  isFieldInvalid(field: string) {
    return (
      (!this.form.get(field).valid && this.form.get(field).touched) ||
      (this.form.get(field).untouched && this.formSubmitAttempt)
    );
  }

  onSubmit() {
    // if (this.form.valid) {
    //   this.authService.login(this.form.value);
    // }
    this.formSubmitAttempt = true;
  }

}

非常感谢你的帮助

您遇到的问题是 formGroup 中 ([ngModel]) 的使用。

如果需要提取值,则必须通过 TS 组件上的 formGroup 变量来完成。

查看有关 Angular 支持页面的更多信息: https://angular.io/guide/reactive-forms

改变这个:

    `<input id="password" matInput type="password" placeholder="Password" formControlName="password" [(ngModel)]="selectedUser.password">`

进入这个:

     `<input id="password" matInput type="password" placeholder="Password" formControlName="password"  (change)="selectedUserChanged($event)">`

     //and add to your ts
     `selectedUserChanged(change: any) {
            this.group.get('password').setValue(change.value);
      }`

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM