Reputation: 39
I want to use ngModel, but I have a problem.
This code is not running and it gives me an error.
This is my code:
contact-form.component.html
:
<div class="container">
<form>
<div class="form-group">
<label for="firstName">First name</label>
<input ngModel #firstName="firstName" (change)="log(firstName)" id="firstName" type="text" class="form-control"/>
</div>
<div class="form-group">
<label for="comment">comment</label>
<textarea id="comment" rows="3" class="form-control"></textarea>
</div>
<button class="btn btn-primary">Enter</button>
</form>
</div>
contact-form.component.ts
:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-contact-form',
templateUrl: './contact-form.component.html',
styleUrls: ['./contact-form.component.css']
})
export class ContactFormComponent implements OnInit {
constructor() { }
ngOnInit() {
}
log(f) {
console.log(f);
}
}
and this error display in console:
Error: Template parse errors:
There is no directive with "exportAs" set to "firstName" (" <div class="form-group">
<label for="firstName">First name</label>
<input ngModel [ERROR ->]#firstName="firstName" (change)="log(firstName)" id="firstName" type="text" class="form-control"/>
"): ng:///AppModule/ContactFormComponent.html@4:23
What can I do?
Upvotes: 1
Views: 510
Reputation: 3387
for your input tag use this. this will breaking down Two-Way data binding.
<input #firstName (change)="log(firstName)" type="text">
- and to display its content use it as interpolation syntax in your template.
{{firstName.value}}
- after you done text input press enter and results will be in interpolation.
Second way of doing this is like..
in this case you need to define your property name in your component class too.
private firstName;
and in your template file
<input [ngModel]="firstName" (ngModelChange)="firstName = $event" >
{{ firstName }}
make sure you import FormsModule
in main app module of your project.
import { FormsModule } from '@angular/forms';
If you want to access template reference variable in your component.ts file then your have to use @ViewChild () directives. and result of this available only in ngAfterViewInit() life cycle method.
@ViewChild ('firstName', { static: false} ) inputRefElm : ElementRef;
ngAfterViewInit(){
console.log(this.inputRefElm.nativeElement.value);
}
Upvotes: 0
Reputation: 837
You can try this:
<div class="form-group">
<label for="firstName">First name</label>
<input [(ngModel)]="firstName" #firstName (change)="log(firstName)" id="firstName" type="text" class="form-control"/>
</div>
Upvotes: 0
Reputation: 14792
modify your input tag in the form like the following :
<input #firstName="ngModel" (change)="log(firstName)"
type="text" class="form-control"/>
Note: if you you want to have Two-way data binding ( [(ngModel)]="propName" ):
<input #firstName="ngModel" (change)="log(firstName)" [(ngModel)]="firstName"
type="text" class="form-control"/>
Upvotes: 1