Creating your first Angular application. Creating a post form

Home » Tutorials » JavaScript » Creating your first Angular application. Creating a post form

In this lesson, we’ll finish building our Angular application by adding a reactive form for creating a new post.

user.ts

@let user = user$ | async;

@if (user) {
  <mat-card>
    <mat-card-header>{{user.name}}</mat-card-header>
    <mat-card-content>
      <p>User email: {{user.email}}</p>
      <p>User phone: {{user.phone}}</p>
    </mat-card-content>
  </mat-card>

  <app-post-form [userId]="user.id"></app-post-form>
}

post-form.ts

import { Component, Input, OnInit } from '@angular/core';
import {MatInputModule} from '@angular/material/input';
import {MatFormFieldModule} from '@angular/material/form-field';
import {MatButtonModule} from '@angular/material/button';
import {FormGroup, ReactiveFormsModule, FormControl, FormBuilder, Validators } from "@angular/forms";
import {PostService} from '../../../../../posts/services/post-service';

interface PostFormGroup {
  postTitle: FormControl<string>;
  postContent: FormControl<string>;
}

@Component({
  selector: 'app-post-form',
  imports: [MatFormFieldModule, MatInputModule, MatButtonModule, ReactiveFormsModule],
  templateUrl: './post-form.html',
  styleUrl: './post-form.scss',
})
export class PostForm implements OnInit{

  protected form!: FormGroup<PostFormGroup>;

  @Input() userId: number = 0;

  constructor(private formBuilder: FormBuilder, private postService: PostService) {
  }

  ngOnInit(): void {
    this.form = this.formBuilder.group({
      postTitle: new FormControl<string>('', {
        nonNullable: true,
        validators: [Validators.required]
      }),
      postContent: new FormControl<string>('', {
        nonNullable: true,
        validators: [Validators.required]
      }),
    })
  }

  protected createPost() {
    if (this.form.invalid || !this.userId) {
      return;
    }
    const formValue = this.form.getRawValue();
    this.postService.createPost(formValue.postTitle, formValue.postContent, this.userId).subscribe();
  }
}

post-form.html

<h1>Create new post</h1>

<form [formGroup]="form" (ngSubmit)="createPost()">
  <div>
  <mat-form-field>
    <mat-label>Enter post title</mat-label>
    <input matInput placeholder="PostService title" formControlName="postTitle">
  </mat-form-field>
  </div>

  <mat-form-field class="example-full-width">
    <mat-label>Enter post content</mat-label>
    <textarea matInput placeholder="PostService content" formControlName="postContent"></textarea>
  </mat-form-field>

  <div>
    <button [disabled]="form.invalid" matButton="filled">Save</button>
  </div>
</form>

post-service.ts

import { HttpClient } from "@angular/common/http";
import { Injectable } from '@angular/core';
import { Observable } from "rxjs";

@Injectable({
  providedIn: 'root',
})
export class PostService {

  private readonly api = 'https://jsonplaceholder.typicode.com/'

  constructor(private http: HttpClient) {
  }

  createPost(title: string, body: string, userId: number): Observable<void> {
    return this.http.post<void>(`${this.api}/posts`, { title, body, userId });
  }

}

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *


The reCAPTCHA verification period has expired. Please reload the page.

Pin It on Pinterest

Share This