0

Angular template variable & NgModel directive variable

Thanks Angular team for bringing such amazing framework. I've been working on AngularJS since 2014. Totally love Angular family.

By now I am working on Angular template-driven forms. Please check below details.

<input type="text" id="input1" name="input1" #input1 [(ngModel)]="data.name" minlength="10">

<input type="text" id="input2" name="input2" #input2="ngModel"  [(ngModel)]="data.name" minlength="10">

<op-single-error-message [field]="input1" [formField]="input2"></op-single-error-message>

  • input1 is template variable.
  • input2 is NgModel directive variable.
  • op-single-error-message is a component which contains two @inputs.
single-error-message.component.ts

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

@Component({
    moduleId: module.id,
    selector: 'op-single-error-message',
    templateUrl: './single-error-message.component.html'
})
export class SingleErrorMessageComponent implements OnInit {
    @Input() form: NgForm;
    @Input() field: any;		// Binds to #input1
    @Input() formField: NgModel;	// Binds to #input2
    @Input() labelTitle: string;

    constructor() { }

    ngOnInit(): void {
    	console.log(`Input1 minlength: ${field.minlength}`);
        console.log(`Input2 minlength: ${formField.minlength}`);		// I KNOW THIS DOES NOT WORK
    }
}

single-error-message.component.html

<span class="help-block" *ngIf="formField.invalid && (form.submitted || formField.dirty || formField.touched)">
    <small class="text-danger" *ngIf="formField.errors.required">{{labelTitle}} is required.</small>
    <small class="text-danger" *ngIf="formField.errors.minlength">{{labelTitle}} is must be at least {{?}} characters long.</small>
</span>

I wanted to display different kind of error message wrapped in this component. In this case, if user wants to change all the required inputs with error message from 'xxx is required' to 'xx cannot be empty', this will be a easy way to handle.

My Question

The formField in SingleErrorMessageComponent is a NgModel variable. Is there any way I can get the DOM just like 'field' does? Because I want to do: - Gets DOM attribute value - Adds / removes attribute

Any help would be appricated. Thanks in advance.

7
  • no, formField references a directive as you said Sep 8, 2017 at 8:14
  • Thanks AngularInDepth.com. Does that mean I have to reference both template variable and NgModel directive variable?
    – Hui
    Sep 8, 2017 at 9:09
  • why do you need ngModel reference? Sep 8, 2017 at 9:13
  • I would to check the touched, valid, pristine properties of ngModel.
    – Hui
    Sep 8, 2017 at 9:31
  • and why do you need field with the reference to DOM node? Sep 8, 2017 at 9:43

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.