title: Angular 2: Check if input in reactive form is empty, enter default value if no input given
body: <p><strong>Edit 2:</strong> Improved upon the partial solution and now it's a complete solution. Yay!</p>
  
  <p><strong>Edit:</strong> Found an almost complete solution. It works, but not quite the way I want it.</p>
  
  <ol>
  <li>It sets a default value from the moment the form is loaded. (not ideal)</li>
  <li>It no longer returns null if the input is empty/deleted (returns an empty string instead)</li>
  </ol>
  
  <p>The solution is posted after the text below.</p>
  
  <hr>
  
  <p>I'm a new student to Angular and I'm making a simple CRUD app to understand how the language works. Currently, I'm learning how to do form validations. </p>
  
  <p>As mentioned in the title, I want to have a validation method that checks if the input is empty, and if it is then to enter a default value. I'm looking for a clean and simple way to do this. Currently here is my code.</p>
  
  <p><strong><code>partial post.component.html</code></strong> (sorry about the multiple lines for the <code>&lt;input&gt;</code>element; I find it easier to read this way)</p>
  
  <pre><code>&lt;modal #modal&gt;
      &lt;form novalidate (ngSubmit)="onSubmit(postForm)" [formGroup]="postForm"&gt;
          &lt;modal-header [show-close]="true"&gt;
              &lt;h4 class="modal-title"&gt;{{modalTitle}}&lt;/h4&gt;
          &lt;/modal-header&gt;
          &lt;modal-body&gt;
  
              &lt;div class="form-group"&gt;
                  &lt;div&gt;
                      &lt;span&gt;Post Title&lt;/span&gt;
                      &lt;input [(ngModel)]="TitleText"
                             type="text" class="form-control"
                             placeholder="Post Title"
                             formControlName="PostTitle"&gt;
                      &lt;div class="error"
                           *ngIf="postForm.get('PostTitle').hasError('required') &amp;&amp; postForm.get('PostTitle').touched"&gt;
                          Title is required
                      &lt;/div&gt;
                      &lt;div class="error"
                           *ngIf="postForm.get('PostTitle').hasError('minlength') &amp;&amp; postForm.get('PostTitle').touched"&gt;
                          Minimum title length is three (3) characters
                      &lt;/div&gt;
                  &lt;/div&gt;
                  &lt;div&gt;
                      &lt;span&gt;Post Slug&lt;/span&gt;
                      &lt;input [ngModel]="TitleText | slugify"
                             type="text"
                             class="form-control"
                             placeholder="Post Slug"
                             formControlName="PostSlug"&gt;
                      &lt;div class="error"
                           *ngIf="postForm.get('PostSlug').hasError('pattern') &amp;&amp; postForm.get('PostSlug').dirty"&gt;
                          URL slug must not contain spaces, special characters or capitalization
                      &lt;/div&gt;
                  &lt;/div&gt;
                  &lt;div&gt;
                      &lt;span&gt;Post Content&lt;/span&gt;
                      &lt;textarea class="form-control"
                                placeholder="Post Content"
                                formControlName="PostContent"&gt;
                      &lt;/textarea&gt;
                  &lt;/div&gt;
                  &lt;div&gt;
                      &lt;span&gt;Post Author&lt;/span&gt;
                      &lt;input type="text"
                             class="form-control"
                             placeholder="Post Author"
                             formControlName="PostAuthor"&gt;
                  &lt;/div&gt;
              &lt;/div&gt;
          &lt;/modal-body&gt;
          &lt;modal-footer&gt;
              &lt;div&gt;
                  &lt;a class="btn btn-default" (click)="modal.dismiss()"&gt;Cancel&lt;/a&gt;
                  &lt;button type="submit"
                          [disabled]="postForm.invalid"
                          class="btn btn-primary"&gt;
                      {{modalBtnTitle}}
                  &lt;/button&gt;
              &lt;/div&gt;
          &lt;/modal-footer&gt;
      &lt;/form&gt;
  &lt;/modal&gt;
  </code></pre>
  
  <p><strong><code>partial post.component.ts</code></strong></p>
  
  <pre><code>    ngOnInit(): void {
  
          this.postForm = this.fb.group({
              PostId: [''],
              PostTitle: [
                  '',
                  [
                      Validators.required,
                      Validators.minLength(3)
                  ]
              ],
              PostSlug: [
                  '',
                  [
                      Validators.required,
                      Validators.pattern('^[a-z0-9-]+$')
                  ]
              ],
              PostContent: [''],
              PostAuthor: ['']
          });
  
          this.LoadPosts();
      }
  </code></pre>
  
  <p>I would like a default value to be passed if the <code>PostContent</code> and <code>PostAuthor</code> fields are left empty. One way that I thought would have worked was to have a default value in the template like so:</p>
  
  <pre><code>&lt;textarea class="form-control"
      placeholder="Post Content"
      formControlName="PostContent"
      value="Not Set"&gt;
  </code></pre>
  
  <p>However this doesn't work and debugging it shows that null is still returned:</p>
  
  <p><a href="https://i.stack.imgur.com/6MArd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6MArd.png" alt="It&#39;s not passing the value hard-coded(ewww...) in the value attribute"></a></p>
  
  <p>Just as well, because that solution would have caused a problem anyway if someone decided to type something then delete it. </p>
  
  <p>For reference, here's the whole <code>post.component.ts</code>:</p>
  
  <pre><code>import { Component, OnInit, ViewChild, Pipe } from '@angular/core';
  import { PostService } from '../Services/post.service';
  import { FormBuilder, FormGroup, Validators } from '@angular/forms';
  import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal';
  import { IPost } from '../Models/post';
  import { DBOperation } from '../Shared/enum';
  import { Observable } from 'rxjs/Rx';
  import { Global } from '../Shared/global';
  
  @Component({
      templateUrl: '/app/Components/post.component.html'
  })
  
  export class PostComponent implements OnInit {
      @ViewChild('modal') modal: ModalComponent;
      posts: IPost[];
      post: IPost;
      msg: string;
      indLoading: boolean = false;
      postForm: FormGroup;
      dbops: DBOperation;
      modalTitle: string;
      modalBtnTitle: string;    
  
      constructor(private fb: FormBuilder, private _postService: PostService) { }
  
      ngOnInit(): void {
  
          this.postForm = this.fb.group({
              PostId: [''],
              PostTitle: [
                  '',
                  [
                      Validators.required,
                      Validators.minLength(3)
                  ]
              ],
              PostSlug: [
                  '',
                  [
                      Validators.required,
                      Validators.pattern('^[a-z0-9-]+$')
                  ]
              ],
              PostContent: [''],
              PostAuthor: ['']
          });
  
          this.LoadPosts();
      }
  
      LoadPosts(): void {
          this.indLoading = true;
          this._postService.get(Global.BASE_POST_ENDPOINT)
              .subscribe(posts =&gt; { this.posts = posts; this.indLoading = false; },
              error =&gt; this.msg = &lt;any&gt;error);
      }
  
      addPost() {
          this.dbops = DBOperation.create;
          this.SetControlsState(true);
          this.modalTitle = "Add New Post";
          this.modalBtnTitle = "Add";
          this.postForm.reset();
          this.modal.open();        
      }
  
      editPost(id: number) {
          this.dbops = DBOperation.update;
          this.SetControlsState(true);
          this.modalTitle = "Edit Post";
          this.modalBtnTitle = "Update";
          this.post = this.posts.filter(x =&gt; x.PostId == id)[0];
          this.postForm.setValue(this.post);
          this.modal.open();
      }
  
      deletePost(id: number) {
          this.dbops = DBOperation.delete;
          this.SetControlsState(false);
          this.modalTitle = "Confirm Post Deletion?";
          this.modalBtnTitle = "Delete";
          this.post = this.posts.filter(x =&gt; x.PostId == id)[0];
          this.postForm.setValue(this.post);
          this.modal.open();
      }
  
      SetControlsState(isEnable: boolean) {
          isEnable ? this.postForm.enable() : this.postForm.disable();
      }
  
      onSubmit(formData: any) {
          this.msg = "";
  
          switch (this.dbops) {
  
              case DBOperation.create:
                  this._postService.post(Global.BASE_POST_ENDPOINT, formData._value).subscribe(
                      data =&gt; {
                          if (data == 1) //Success
                          {
                              this.msg = "Post successfully added.";
                              this.LoadPosts();
                          }
                          else {
                              this.msg = "There is an issue with creating the post, please contact the system administrator!"
                          }
  
                          this.modal.dismiss();
                      },
                      error =&gt; {
                          this.msg = error;
                      }
                  );
                  break;
  
              case DBOperation.update:
                  this._postService.put(Global.BASE_POST_ENDPOINT, formData._value.PostId, formData._value).subscribe(
                      data =&gt; {
                          if (data == 1) //Success
                          {
                              this.msg = "Post successfully updated.";
                              this.LoadPosts();
                          }
                          else {
                              this.msg = "There is an issue with updating the post, please contact the system administrator!"
                          }
  
                          this.modal.dismiss();
                      },
                      error =&gt; {
                          this.msg = error;
                      }
                  );
                  break;
  
              case DBOperation.delete:
                  this._postService.delete(Global.BASE_POST_ENDPOINT, formData._value.PostId).subscribe(
                      data =&gt; {
                          if (data == 1) //Success
                          {
                              this.msg = "Post successfully deleted.";
                              this.LoadPosts();
                          }
                          else {
                              this.msg = "There is an issue with deleting the post, please contact the system administrator!"
                          }
  
                          this.modal.dismiss();
                      },
                      error =&gt; {
                          this.msg = error;
                      }
                  );
                  break;
          }
      }
  }
  </code></pre>
  
  <p>Should I look into adding the Null check in the <code>onSubmit</code> method (or is it function?) instead?</p>
  
  <hr>
  
  <blockquote>
    <p>Potential solution, needs improvement</p>
  </blockquote>
  
  <p>So in the <code>addPost()</code> part of the <code>post.component.ts</code> above, I added two lines:</p>
  
  <pre><code>    addPost() {
          this.dbops = DBOperation.create;
          this.SetControlsState(true);
          this.modalTitle = "Add New Post";
          this.modalBtnTitle = "Add";
          this.postForm.reset();
          this.modal.open();
          this.postForm.controls['PostContent'].setValue('not set'); //this here is the magic
          this.postForm.controls['PostAuthor'].setValue('not credited'); // and this too
      }
  </code></pre>
  
  <p>This basically sets the value from the moment the modal box to enter a new entry is loaded. The value can be deleted from the input and when that happens it's replaced with an empty string. I don't know where this empty string value is coming from. </p>