Reputation: 451
How can I be able to post may data using this angular ngForm? I really have trouble doing this part I need your experience in this one.
I added my service.ts below. I am really new to this one I hope anyone can give me insights.
Thank you in advance guys!!
app.component.ts
import { Component } from '@angular/core';
import { NgForm } from '@angular/forms';
import { TextService } from './text.service'
import { Text } from './text';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
providers: [TextService]
})
export class AppComponent {
constructor(public textService:TextService){}
ngOnInit(){
this.getTexts()
}
getTexts(){
this.textService.getTexts()
.subscribe(( res ) => {
this.textService.texts = res as Text[];
})
}
postText(formValue){
this.textService.postText(formValue).subscribe( res => {
this.getTexts();
this.textService.selectedText = new Text()
});
}
}
app.service.ts
import { Component } from '@angular/core';
import { NgForm } from '@angular/forms';
import { TextService } from './text.service'
import { Text } from './text';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
providers: [TextService]
})
export class AppComponent {
constructor(public textService:TextService){}
ngOnInit(){
this.getTexts()
}
getTexts(){
this.textService.getTexts()
.subscribe(( res ) => {
this.textService.texts = res as Text[];
})
}
postText(formValue){
this.textService.postText(formValue).subscribe( res => {
this.getTexts();
this.textService.selectedText = new Text()
});
}
}
app.components.html
<div *ngFor="let text of textService.texts">
<h1> {{ text.some_text }} </h1>
</div>
<form #textForm="ngForm" (ngSubmit)="postText(textForm.value)">
<label for="some_text">First name:</label><br>
<input type="text" id="some_text" name="some_text" #name="ngModel" [(ngModel)]="textService.selectedText.some_text"><br>
<input type="submit" value="Submit">
</form>
Upvotes: 0
Views: 432
Reputation: 979
Your typescript is not well formed for a start.
postText(textForm=NgForm){
.subscribe((res) => {
this.getTexts()
this.textService.selectedText = new Text()
})
You are subscribing to nothing on the first line inside this method. Instead you should use presumably your text service (where I assume you use http) to post the form value which you have passed in from the html. Something like the following:
postText(formValue){
this.textService.post(formValue).subscribe( res => {
this.getTexts();
this.textService.selectedText = new Text()
});
}
Upvotes: 1