0

I'm using Angular Material and trying to display the errors. The problem is that I can't connect to the actual value.

This is my component.ts code:

myForm!: FormGroup;

constructor(private fb: FormBuilder) { }

  ngOnInit() {
    this.myForm= this.fb.group({
      users: this.fb.array([])
    });
  }

//getting users as a form arr
  get Users(){
    return this.myForm.get('users') as FormArray;
  }

//adding new dynamic forms
 addUser(){
      const user = this.fb.group({
      fname: [null, Validators.required],
      lname: ['', Validators.required],
      updateOn: 'blur'
    })
    this.Users.push(user);
  }

And this is my html template:

<div *ngFor="let user of Users.controls; let i = index" [formGroupName]="i">
<mat-form-field>
  <input matInput placeholder="first name" formControlName="fname">

  <mat-error *ngIf="user['controls'].fname.hasError('required')">
        Enter the first name
   </mat-error>
</mat-form-field>
</div>

I also tried to write get function for this code, but it turned out like this:

 get User() {
    return (this.myForm.controls.users as FormGroup).controls;
  }

And then tried to write in html like:

*ngIf="user['User'].fname.hasError('required')"

it still shows this error: error TS7052: Element implicitly has an 'any' type because type 'AbstractControl' has no index signature. Did you mean to call 'get'?

How can I bind to those values?

1
  • Is my answer helpful for you? Commented Jul 19, 2021 at 13:21

1 Answer 1

1

You have written condition on mat-error is wrong. It should be as following:

<div [formGroup]="myForm">
  <div formArrayName="users">
    <div *ngFor="let user of Users.controls; let i = index" [formGroupName]="i">
      <mat-form-field>
        <input matInput placeholder="first name" formControlName="fname">
        <mat-error *ngIf="user?.get('fname')?.errors">
          Enter the first name
        </mat-error>
      </mat-form-field>
    </div>
  </div>
</div>
Sign up to request clarification or add additional context in comments.

1 Comment

If you're using material and mat-error and you has an unique error you needn't use *ngIf, material error is yet take account of this

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.