Home > OS >  main.ts:11 ERROR Error: No value accessor for form control with name: 'password'
main.ts:11 ERROR Error: No value accessor for form control with name: 'password'

Time:10-31

Try to split signup and login forms and create separate password component for password and password conformation. Generally, I have form control in form. And when I try to put inside component all necessary properties i get error. It's look like... password.component.html

<mat-form-field appearance="fill" hintLabel="{{ hintLabel }}">
  <mat-label>{{ titleOfField }}</mat-label>
  <input
    matInput
    [type]="isPasswordHidden ? 'password' : 'text'"
    [name]="name"
    [formControlName]="formControlName"
  />
  <button
    mat-icon-button
    matSuffix
    (click)="togglePassVisibility($event)"
    [attr.aria-label]="'Hide password'"
    [attr.aria-pressed]="isPasswordHidden"
    
  >
    <mat-icon>{{
      isPasswordHidden ? "visibility_off" : "visibility"
    }}</mat-icon>
  </button>
</mat-form-field>

password.component.ts

import { Component, Input, OnInit } from '@angular/core';

@Component({
  selector: 'app-password-field',
  templateUrl: './password-field.component.html',
  styleUrls: ['./password-field.component.scss'],
})
export class PasswordFieldComponent implements OnInit {
  isPasswordHidden = true;
  @Input() titleOfField!: string;
  @Input() hintLabel!: string;
  @Input() name!: string;
  @Input() formControlName!: string;
  constructor() {}

  ngOnInit(): void {}

  togglePassVisibility(e: Event) {
    e.preventDefault();
    this.isPasswordHidden = !this.isPasswordHidden;
  }
}

and fragment from form component

<app-wrapper>
  <form  (submit)="userLoginClick()" [formGroup]="form">
    <app-password-field
      titleOfField="Enter your password"
      hintLabel="Use at least 6 symbols"
      name="password"
      formControlName="password"
    ></app-password-field>
</app-wrapper>

CodePudding user response:

Two options to do here. You can implement ControlValueAccessor in case you want to be able to use formControlName="password" in the child tag as you are doing it currently. Here is an SO answer for that purpose: https://stackoverflow.com/a/62260210/6294072

The other option is to pass the form control itself to the child, like so:

<app-password-field
  [formCtrl]="form.get('password')"
></app-password-field>

And then the child would take the control:

@Input() formCtrl!: FormControl

and used in the template like:

<input
  matInput
  [type]="isPasswordHidden ? 'password' : 'text'"
  [name]="name"
  [formControl]="formCtrl"
/>
  • Related