htmlangulartypescriptinputbinding

Validation using if statement using input binding in Angular


I am creating a reusable component for Input field. I created a Boolean tag named "IsValid" inside my typescript file to show validation message.

My typescript file

export class InputControlsComponent implements OnInit {

  @Input() IsValid;
  @Input() className;
  @Input() controlName;
  @Input() inputType;

  constructor() { }

  ngOnInit() {
  }

}

Html File

<div>
  <input type="{{inputType}}" class="{{className}}" >
  <span class="error-message" *ngIf="!IsValid">This Field is required</span>
</div>

How it is being used

<div>
          <label>Name</label>
          <app-input-controls  inputType="text"  controlName="Address" className="form-control" IsValid = "false">
          </app-input-controls>
</div>

I am able to change the value of the Boolean tag of typescript file but the error message is not changing on change of the Boolean tag.


Solution

  • You can use ngModel like [(IsValid)],

    If you use ngModel,your model is binding two way.

    For example set your html

    <app-input-validation  [inputType]="'text'"  [controlName]="Address" [className]="form-control" [(IsValid)]="isValidDate">
    </app-input-validation>
    

    You can set isValid property on parent component whenever you want.

    Only write this.isValidText=true;

    Please examine example