Beyond the Tutorials: A Realistic Look at Coding in the Real World – Part 3
Tags: programming, tutorial, dotnetcore, angular
Published: 2023-01-28 12:24:41

<!-- wp:paragraph -->
<p>Programming tutorials shows us a land of promise where everything happens as you think; as soon as you think. But real world doesn’t work that way most of the times. Here; you spend hours debugging some CORS error or thinking why your database table Id column is not auto-incrementing. For the last 2 days; I am participating in a coding&nbsp;<a href="https://asifulhaque.com/common-interview-questions-for-sr-software-engineers-and-how-to-answer-them/">interview</a>&nbsp;which spans 2 days and these series of blog is based on that experience – what am I thinking at each stage; what is the issue and how I am resolving them. This is the third part of that.</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2>Designing the rest of the Angular UI</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>What we left are adding a navigation on top of the page; adding the pages that will be responsible for the UI; and designing the pages in reactive form (Yes; we hate ourself). </p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>Reactive Forms:</h3>
<!-- /wp:heading -->

<!-- wp:heading {"level":4} -->
<h4>Pros:</h4>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><!-- wp:list-item -->
<li>They provide more control over the form and its elements, as you can programmatically manipulate the form and its elements.</li>
<!-- /wp:list-item -->

<!-- wp:list-item -->
<li>They are more efficient as they only update the form and its elements when explicitly told to do so.</li>
<!-- /wp:list-item -->

<!-- wp:list-item -->
<li>They are better suited for handling complex forms with many fields and validation rules.</li>
<!-- /wp:list-item --></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":4} -->
<h4>Cons:</h4>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><!-- wp:list-item -->
<li>They can be more difficult to set up and may require more code to implement.</li>
<!-- /wp:list-item -->

<!-- wp:list-item -->
<li>They may not be as intuitive to work with for developers who are not familiar with the reactive programming paradigm.</li>
<!-- /wp:list-item --></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":4} -->
<h4>Example:</h4>
<!-- /wp:heading -->

<!-- wp:preformatted -->
<pre class="wp-block-preformatted"><code>this.form = this.fb.group({
  name: ['', Validators.required],
  email: ['', [Validators.required, Validators.email]],
  password: ['', Validators.required],
});
</code></pre>
<!-- /wp:preformatted -->

<!-- wp:heading {"level":3} -->
<h3>Template-Driven Forms:</h3>
<!-- /wp:heading -->

<!-- wp:heading {"level":4} -->
<h4>Pros:</h4>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><!-- wp:list-item -->
<li>They are easier to set up and may require less code to implement.</li>
<!-- /wp:list-item -->

<!-- wp:list-item -->
<li>They are more intuitive for developers who are not familiar with the reactive programming paradigm.</li>
<!-- /wp:list-item --></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":4} -->
<h4>Cons:</h4>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><!-- wp:list-item -->
<li>They provide less control over the form and its elements, as the data binding is handled automatically.</li>
<!-- /wp:list-item -->

<!-- wp:list-item -->
<li>They may not be as efficient as reactive forms, as they update the form and its elements on every change event.</li>
<!-- /wp:list-item -->

<!-- wp:list-item -->
<li>They are less suitable for handling complex forms with many fields and validation rules.</li>
<!-- /wp:list-item --></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":4} -->
<h4>Example:</h4>
<!-- /wp:heading -->

<!-- wp:preformatted -->
<pre class="wp-block-preformatted"><code>&lt;form #form="ngForm" (ngSubmit)="submit(form)"&gt;
  &lt;input name="name" ngModel required&gt;
  &lt;input name="email" ngModel required email&gt;
  &lt;input name="password" ngModel required&gt;
  &lt;button type="submit"&gt;Submit&lt;/button&gt;
&lt;/form&gt;
</code></pre>
<!-- /wp:preformatted -->

<!-- wp:heading {"level":3} -->
<h3>Why Reactive over Template-Driven</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Reactive Forms provide more control over handling complex forms with many fields and validation rules as they allow you to programmatically manipulate the form and its elements. This allows you to create a form structure that is more modular and reusable, making it easier to manage and maintain.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>For example, in a complex form with many fields and validation rules, you can create a custom form control component for each field and reuse it throughout the form. This allows you to keep the form code more organized and maintainable, making it easier to add, remove, or update fields and validation rules.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Reactive forms also offer a powerful way of handling validation. With reactive forms, you can define validation rules for each form control and even for the form itself. This allows you to centralize your validation logic and keep it organized. You can also use the built-in Angular validation directives such as <code>required</code>, <code>min</code>, <code>max</code>, and <code>pattern</code> and you can also create your custom validators to apply more complex validation rules.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>For example, here is a sample of how to create a custom validator and use it with a form control:</p>
<!-- /wp:paragraph -->

<!-- wp:preformatted -->
<pre class="wp-block-preformatted"><code>import { FormControl } from '@angular/forms';

function validateEmail(c: FormControl) {
  let EMAIL_REGEXP = /^[a-z0-9!#$%&amp;'*+\/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i;

  return EMAIL_REGEXP.test(c.value) ? null : {
    validateEmail: {
      valid: false
    }
  };
}

this.form = new FormGroup({
  email: new FormControl('', [validateEmail])
});</code></pre>
<!-- /wp:preformatted -->

<!-- wp:paragraph -->
<p>One problem that we run into when we design user-list.ts like this -</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { HttpClientService } from 'src/app/http-client.service';
import { UserModel } from '../../../../models/user';

@Component({
  selector: 'app-use-list',
  templateUrl: './use-list.component.html',
  styleUrls: &#91;'./use-list.component.scss']
})
export class UseListComponent implements OnInit {
  userList = UserModel&#91;];
  constructor(client: HttpClientService) {
    client.getData("user").subscribe((res: UserModel&#91;]) =&gt; {
      console.log(res);
      this.userList = res;
    });
  }

  ngOnInit(): void {

  }
}
</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>Where we declare UserModel in a model file; we get the following error - <code>Element implicitly has an 'any' type because expression of type 'any' can't be used to index type 'typeof UserModel'.</code> Most probably our use of [] after UserModel is causing the issue. Changing the code like below fixes the issue - </p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { HttpClientService } from 'src/app/http-client.service';
import { UserModel } from '../../../../models/user';

@Component({
  selector: 'app-use-list',
  templateUrl: './use-list.component.html',
  styleUrls: &#91;'./use-list.component.scss']
})
export class UseListComponent implements OnInit {
  userList: UserModel&#91;] = &#91;];
  constructor(client: HttpClientService) {
    client.getData("user").subscribe((res) =&gt; {
      console.log(res);
      this.userList = res as UserModel&#91;];
    });
  }

  ngOnInit(): void {

  }
}
</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>We have since changed the code and our user-create.html file looks like this - </p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>&lt;div class="container"&gt;
  &lt;form &#91;formGroup]="userForm"&gt;
    &lt;div class="form-group"&gt;
      &lt;label for="name"&gt;Name&lt;/label&gt;
      &lt;input type="text" class="form-control" id="name" formControlName="name"&gt;
    &lt;/div&gt;
    &lt;div class="form-group"&gt;
      &lt;label for="email"&gt;Email&lt;/label&gt;
      &lt;input type="email" class="form-control" id="email" formControlName="email"&gt;
    &lt;/div&gt;
    &lt;div class="form-group"&gt;
      &lt;label for="mobile"&gt;Mobile&lt;/label&gt;
      &lt;input type="tel" class="form-control" id="mobile" formControlName="mobile"&gt;
    &lt;/div&gt;
    &lt;div class="form-group form-check"&gt;
      &lt;input type="checkbox" class="form-check-input" id="is_active" formControlName="isActive"&gt;
      &lt;label class="form-check-label" for="is_active"&gt;Is Active&lt;/label&gt;
    &lt;/div&gt;
    &lt;button type="submit" class="btn btn-primary" (click)="save()"&gt;Save&lt;/button&gt;
    &lt;!-- &lt;button type="button" class="btn btn-secondary" (click)="cancel()"&gt;Cancel&lt;/button&gt; --&gt;
  &lt;/form&gt;
&lt;/div&gt;
</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>which is throwing an error - Can't bind to 'formGroup' since it isn't a known property of 'form'.  <br>When we add<br><code> import { FormsModule, ReactiveFormsModule } from '@angular/forms';</code><br>in app.module.ts file and in imports list added - <br><code>FormsModule,<br>ReactiveFormsModule</code><br>This issue is gone however.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>The code unto this will be available in branch - version_1.</p>
<!-- /wp:paragraph -->

<!-- wp:image {"id":933,"sizeSlug":"large","linkDestination":"none"} -->
<figure class="wp-block-image size-large"><img src="https://asifulhaque.com/wp-content/uploads/2023/01/is-programming-hard-a-guide-to-getting-started-in-2022-scaled-1-1024x819.jpeg" alt="Tutorials_2" class="wp-image-933"/></figure>
<!-- /wp:image -->

<!-- wp:heading -->
<h2>The Struggle Begins!</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>When we submit the form; it shows an error - <code>An error occurred while saving the entity changes. See the inner exception for details.</code> &amp; <code>Cannot insert the value NULL into column 'id', table 'dev_test.dbo.user'; column does not allow nulls. INSERT fails.</code> <br>Which is understandable! I mean; we haven't given the object any id value. <br>But shouldn't our db take care of that? <br><br>Looking into our db script; we can see that we have made id primary key; but we forgot to increment it; specifically forgot to add <code>IDENTITY(1,1) NOT NULL</code> to our tables.<br>So we need to add some ways to drop and create tables and setting the identity to each id column. <br>And our database file looks like this -</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>IF OBJECT_ID(N'dbo.invitation', N'U') IS NOT NULL  
   DROP TABLE &#91;dbo].invitation;  
GO

IF OBJECT_ID(N'dbo.submission', N'U') IS NOT NULL  
   DROP TABLE &#91;dbo].submission;  
GO

IF OBJECT_ID(N'dbo.answer', N'U') IS NOT NULL  
   DROP TABLE &#91;dbo].answer;  
GO

IF OBJECT_ID(N'dbo.question', N'U') IS NOT NULL  
   DROP TABLE &#91;dbo].question;  
GO

IF OBJECT_ID(N'dbo.survey', N'U') IS NOT NULL  
   DROP TABLE &#91;dbo].survey;  
GO


IF OBJECT_ID(N'dbo.&#91;user]', N'U') IS NOT NULL  
   DROP TABLE &#91;dbo].&#91;user];  
GO


CREATE TABLE &#91;user]
(
    id INT PRIMARY KEY  IDENTITY(1,1),
    email VARCHAR(255) NOT NULL UNIQUE,
    mobile VARCHAR(15) NOT NULL,
    isActive BIT NOT NULL,
    role VARCHAR(255) NOT NULL
);

CREATE TABLE survey
(
    id INT PRIMARY KEY IDENTITY(1,1),
    title VARCHAR(255) NOT NULL,
    created_date DATETIME NOT NULL,
    updated_date DATETIME NOT NULL
);

CREATE TABLE question
(
    id INT PRIMARY KEY IDENTITY(1,1),
    survey_id INT NOT NULL,
    text NVARCHAR(MAX) NOT NULL,
    FOREIGN KEY (survey_id) REFERENCES survey(id)
);

CREATE TABLE answer
(
    id INT PRIMARY KEY IDENTITY(1,1),
    question_id INT NOT NULL,
    text NVARCHAR(MAX) NOT NULL,
    is_correct BIT NOT NULL,
    FOREIGN KEY (question_id) REFERENCES question(id)
);


CREATE TABLE invitation
(
    id INT PRIMARY KEY IDENTITY(1,1),
    survey_id INT NOT NULL,
    user_id INT NOT NULL,
    invitation_link NVARCHAR(MAX) NOT NULL,
    FOREIGN KEY (survey_id) REFERENCES survey(id),
    FOREIGN KEY (user_id) REFERENCES &#91;user](id)
);


CREATE TABLE submission
(
    id INT PRIMARY KEY IDENTITY(1,1),
    survey_id INT NOT NULL,
    user_id INT NOT NULL,
    answer1 INT NOT NULL,
    answer2 INT NOT NULL,
    answer3 INT NOT NULL,
    score INT NOT NULL,
    FOREIGN KEY (survey_id) REFERENCES survey(id),
    FOREIGN KEY (user_id) REFERENCES &#91;user](id)
);</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>We then proceed to design the rest of the UI as well. The complete code is given by version_2.<br>One issue we stumbled upon is this. When we design the survey front end like this -</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>And ts file like this -</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>import { Component, OnInit } from '@angular/core';
import { FormArray, FormControl, FormGroup } from '@angular/forms';
import { HttpClientService } from 'src/app/http-client.service';

@Component({
  selector: 'app-survey-add',
  templateUrl: './survey-add.component.html',
  styleUrls: &#91;'./survey-add.component.scss']
})
export class SurveyAddComponent implements OnInit {
  _client: HttpClientService;
  surveyForm = new FormGroup({
    title: new FormControl(),
    Questions: new FormArray(
      &#91;
        new FormGroup(
          {
            Text: new FormControl(),
            Answers: new FormArray(
              &#91;
                new FormGroup(
                  {
                    Text: new FormControl(),
                    isCorrect: new FormControl(),
                  }
                ),
                new FormGroup(
                  {
                    Text: new FormControl(),
                    isCorrect: new FormControl(),
                  }
                ),
                new FormGroup(
                  {
                    Text: new FormControl(),
                    isCorrect: new FormControl(),
                  }
                ),
                new FormGroup(
                  {
                    Text: new FormControl(),
                    isCorrect: new FormControl(),
                  }
                ),
              ]
            )
          }
        ),
        new FormGroup(
          {
            Text: new FormControl(),
            Answers: new FormArray(
              &#91;
                new FormGroup(
                  {
                    Text: new FormControl(),
                    isCorrect: new FormControl(),
                  }
                ),
                new FormGroup(
                  {
                    Text: new FormControl(),
                    isCorrect: new FormControl(),
                  }
                ),
                new FormGroup(
                  {
                    Text: new FormControl(),
                    isCorrect: new FormControl(),
                  }
                ),
                new FormGroup(
                  {
                    Text: new FormControl(),
                    isCorrect: new FormControl(),
                  }
                ),
              ]
            )
          }
        ),
        new FormGroup(
          {
            Text: new FormControl(),
            Answers: new FormArray(
              &#91;
                new FormGroup(
                  {
                    Text: new FormControl(),
                    isCorrect: new FormControl(),
                  }
                ),
                new FormGroup(
                  {
                    Text: new FormControl(),
                    isCorrect: new FormControl(),
                  }
                ),
                new FormGroup(
                  {
                    Text: new FormControl(),
                    isCorrect: new FormControl(),
                  }
                ),
                new FormGroup(
                  {
                    Text: new FormControl(),
                    isCorrect: new FormControl(),
                  }
                ),
              ]
            )
          }
        ),
      ]
    ),
  });

  constructor(client: HttpClientService) { this._client = client }

  ngOnInit(): void {
  }

  getQuestionControls() {
    return this.surveyForm.controls&#91;'Questions'] as FormArray;
  }

  getAnswerControls(question: any) {
    console.log(question&#91;'Answers'] as FormArray);
    return question&#91;'Answers'] as FormArray;
  }

  selectAnswer(i: number, j: number) {
  }

  save() {
    this._client.postData("survey", this.surveyForm.value).subscribe((res) =&gt; {
      console.log(res);
    });
  }

  cancel() {
    this.surveyForm = new FormGroup({
      title: new FormControl(),
      Questions: new FormArray(
        &#91;
          new FormGroup(
            {
              Text: new FormControl(),
              Answers: new FormArray(
                &#91;
                  new FormGroup(
                    {
                      Text: new FormControl(),
                      isCorrect: new FormControl(),
                    }
                  ),
                  new FormGroup(
                    {
                      Text: new FormControl(),
                      isCorrect: new FormControl(),
                    }
                  ),
                  new FormGroup(
                    {
                      Text: new FormControl(),
                      isCorrect: new FormControl(),
                    }
                  ),
                  new FormGroup(
                    {
                      Text: new FormControl(),
                      isCorrect: new FormControl(),
                    }
                  ),
                ]
              )
            }
          ),
          new FormGroup(
            {
              Text: new FormControl(),
              Answers: new FormArray(
                &#91;
                  new FormGroup(
                    {
                      Text: new FormControl(),
                      isCorrect: new FormControl(),
                    }
                  ),
                  new FormGroup(
                    {
                      Text: new FormControl(),
                      isCorrect: new FormControl(),
                    }
                  ),
                  new FormGroup(
                    {
                      Text: new FormControl(),
                      isCorrect: new FormControl(),
                    }
                  ),
                  new FormGroup(
                    {
                      Text: new FormControl(),
                      isCorrect: new FormControl(),
                    }
                  ),
                ]
              )
            }
          ),
          new FormGroup(
            {
              Text: new FormControl(),
              Answers: new FormArray(
                &#91;
                  new FormGroup(
                    {
                      Text: new FormControl(),
                      isCorrect: new FormControl(),
                    }
                  ),
                  new FormGroup(
                    {
                      Text: new FormControl(),
                      isCorrect: new FormControl(),
                    }
                  ),
                  new FormGroup(
                    {
                      Text: new FormControl(),
                      isCorrect: new FormControl(),
                    }
                  ),
                  new FormGroup(
                    {
                      Text: new FormControl(),
                      isCorrect: new FormControl(),
                    }
                  ),
                ]
              )
            }
          ),
        ]
      ),
    });
  }
}
</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>The output is like this - </p>
<!-- /wp:paragraph -->

<!-- wp:image {"id":897,"sizeSlug":"large","linkDestination":"none"} -->
<figure class="wp-block-image size-large"><img src="https://asifulhaque.com/wp-content/uploads/2023/01/image-4-1024x275.png" alt="" class="wp-image-897"/><figcaption class="wp-element-caption">Problematic UI</figcaption></figure>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>As we can see; it's not showing the answers or anything related to that.<br>Rewriting the ts file as - </p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>  getAnswerControls(question: any) {
    console.log(question&#91;'Answers'] as FormArray);
    return question&#91;'Answers'];
  }</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>And the html file as - </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Fixed the issue.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><strong>Other episodes in this series:</strong><br><a href="https://asifulhaque.com/when-programming-tutorials-doesnt-work-part-1/">First Part</a><br><a href="https://asifulhaque.com/beyond-the-tutorials-a-realistic-look-at-coding-in-the-real-world-part-2/">Second Part</a><br><a href="https://asifulhaque.com/beyond-the-tutorials-a-realistic-look-at-coding-in-the-real-world-part-3/">Third Part</a><br><a href="https://asifulhaque.com/beyond-the-tutorials-a-realistic-look-at-coding-in-the-real-world-part-4/">Fourth Part</a><br>And the code is given is updated into - <br><a href="https://github.com/asifbuetcse/dev-test" target="_blank" rel="noreferrer noopener">Github</a></p>
<!-- /wp:paragraph -->