The template file

From Solution Explorer, right-click on the /ClientApp/app/components/quiz/ folder and add a new HTML file; call it quiz-list.component.html, and replace the sample code with the following:

<h2>{{title}}</h2>
<ul class="quizzes">
<li *ngFor="let quiz of quizzes"
[class.selected]="quiz === selectedQuiz"
(click)="onSelect(quiz)">
<span>{{quiz.Title}}</span>
</li>
</ul>
It's important to understand that we're free to use any filename we want for the template file, as long as it reflects the value we used in the templateUrl property within the quiz-list.component.ts file. We can even share the same template among two (or more) different components. However, the Angular best practices suggest that we use the same name of the component, as it will lead to a cleaner, more readable code structure.

Among these few lines, we can see the two things we were looking for:

  • The HTML code to render the quiz list, handled with a ngFor cycle that will iterate through the quizzes array and create a number of <li> elements as soon as it is filled by the .subscribe() method of HttpClient in the component class source code
  • The (click) event handler that will raise a call to the onSelect() method, where the currently iterated quiz is passed as a parameter

There are also a couple of other things worth noting:

  • In line 4, we added a simple logic that will decorate the <li> element hosting the selected quiz with the selected CSS class so that we can style it in a different way.
  • In line 1 and line 6, we make use of the double-curly braces of interpolation, an important Angular feature that allows us to insert calculated strings into the text between HTML element tags and within attribute assignments. The text between the braces is almost always the name of a component property; the whole block will be replaced with the string value of the corresponding component property. This means that, in our specific scenario, we can expect to see the component title between the <h2> element in line 1 and the quiz title between the <span> element in line 6.

The double-curly braces of interpolation are part of the Angular Template Syntax, a collection of expressions, shortcuts, and keywords that can be used in templates--along with HTML--to grant them additional features. We'll introduce more of them later on, as soon as we need to use them. Nonetheless, if you just can’t wait to see what else is in store, you can take a look at the official documentation, which is available on the Angular website at the following address:

https://angular.io/guide/template-syntax

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.12.34