Reputation: 1597
I am trying to pass value of the input field to the component class. But it does not seem to be working. Please find the code below:
todoinput.component.html
<mat-card>
<form>
<mat-form-field class="example-full-width">
<input matInput type="text" name="todo" placeholder="Enter a todo">
</mat-form-field>
<button mat-raised-button color="primary" type="button" (click)="addTodo(todo.value)">Add Todo
</button>
</form>
</mat-card>
todoinput.component.ts
addTodo(text) {
this._todosService.addTodo({
text: text,
}).subscribe((todo) => {
return this.newTodo.emit(todo);
})
}
But clicking on the button throws the error below:
ERROR TypeError: Cannot read property 'value' of undefined
at Object.eval [as handleEvent] (TodoinputComponent.html:7)
at handleEvent (core.js:10258)
I am using angular material framework for rendering the elements. Could anyone let me know what am I doing wrong here ?
Thanks
Upvotes: 6
Views: 37756
Reputation: 2027
An alternative that I think might be easier to work with is to have a backing field and bind to it:
html:
<mat-card>
<form>
<mat-form-field class="example-full-width">
<input [(ngModel)]="todo" matInput type="text" name="todo" placeholder="Enter a todo">
</mat-form-field>
<button mat-raised-button color="primary" type="button" (click)="addTodo()">Add Todo
</button>
</form>
</mat-card>
ts
todo = '';
addTodo() {
if (!this.todo) {
return;
}
this._todosService.addTodo({
text: this.todo,
}).subscribe((todo) => {
this.todo = '';
return this.newTodo.emit(todo);
})
}
This way its easier to do things like validate they entered a value, and reset the field to empty after a successful submit.
Upvotes: 0
Reputation: 305
Use #todo in element:
<input matInput type="text" name="todo" #todo placeholder="Enter a todo">
And use:
{{ todo.value }}
Upvotes: -1
Reputation: 7455
Try to add #todo
to the input. After that angular should be able to acces to the right input. Without that it gets undefined variable instead.
<mat-card>
<form>
<mat-form-field class="example-full-width">
<input #todo matInput type="text" name="todo" placeholder="Enter a todo">
</mat-form-field>
<button mat-raised-button color="primary" type="button" (click)="addTodo(todo.value)">Add Todo
</button>
</form>
</mat-card>
Upvotes: 11