Search code examples
angularangular-directive

Custom component Interpolation


My Custom Component is:

Template:
=============

<div *ngIf="!errorInput">
    <div>
        {{ errorMessage }}
    </div>
</div>

Component
===========

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

@Component({
  selector: 'app-validate',
  templateUrl: './form-validate.component.html',
  styleUrls: ['./form-validate.component.css'],
})
export class FormValidateComponent implements OnInit {
  @Input() errorMessage: string;
  @Input() errorInput: boolean;

  constructor() {}

  ngOnInit(): void {}
}

I am using the above to validate the form and display the validation error message.

I am using this custom component as follows

 <label>Description</label>
<input type="text" formControlName="description" pInputText
    style="border-color: black;">

<app-validate
    [errorInput]="isValid('description', this.formGroup)"
    [errorMessage]="displayErrorMessage('description','Enter description', this.formGroup)">
</app-validate>
                      

isValid method validates based on the Validator and displayErrorMessage returns the error message.

This is working as expected.

In my requirement, I have to generate form groups and form fields dynamically, and validate the same.

I am able to create form groups, fields, and validators.

Form control name will get replace based on the dynamic values.

<div class="col-md-6"
    *ngFor="let attribute of attributeList; let attributeLength = count; let attributeCount = index;">

    <label> {{attribute.attributeName}}</label>

    <input type="text" formControlName="{{attribute.attributeName}}" pInputText
    style="border-color: black;">

    <app-validate
    [errorInput]="isValid('{{attribute.attributeName}}', this.formGroup)"
    [errorMessage]="displayErrorMessage('{{attribute.attributeName}}','Enter as per validator ', this.formGroup)">
    </app-validate>


</div>                               ​

In this above code {{attribute.attributeName}} is getting replaced properly everywhere except in the following


   ​<app-validate
    [errorInput]="isValid(**'{{attribute.attributeName}}'**, this.formGroup)"
    [errorMessage]="displayErrorMessage(**'{{attribute.attributeName}}'**,'Enter as per validator ', this.formGroup)">
   ​</app-validate>

If i log, the first parameter of isValid, i am getting {{attribute.attributeName}} instead of the actual value.

For the custom component, will it get replaced?

Can you please help me to resolve this?


Solution

  • Your're making a string of it instead of using the value. Do it this way

    <app-validate
        [errorInput]="isValid(attribute.attributeName, this.formGroup)"
        [errorMessage]="displayErrorMessage(attribute.attributeName,'Enter as per validator ', this.formGroup)">
    </app-validate>
    

    That should do the trick.