InterviewSolution
| 1. |
Explain structural directives in Angular? |
|
Answer» Structural directives are responsible for HTML layout. They shape or reshape the DOM's structure, typically by adding, removing, or manipulating elements. As with other directives, you apply a structural directive to a host element. The directive then does whatever it's supposed to do with that host element and its descendants. Structural directives are easy to recognize. An ASTERISK (*) PRECEDES the directive attribute name. There are two primary structural directives in Angular - ngFor and ngIf. NgIf is very useful if you want to show or hide parts of your application based on a condition. For example, if you want to show or hide an element on the page based on the value of a VARIABLE, you can do that using ngIf. Let’s have a look at the code. TS Code import { Component } from '@angular/core'; @Component({ selector: 'app-example', templateUrl: './example.component.html', styleUrls: ['./example.component.css'] }) export class ExampleComponent { show: boolean = true; }HTML Code <p>Show this all the time</p> <p *ngIf="show"> Show this only if "show" is true </p>When you TEST the above component, you will only the second p tag in the page when the value of the boolean property “show” is true. Please note that the p element is not only hidden, but is completely removed from the DOM. The great advantage of this is, that this method is not interfering with any CSS-Style-sheets at all. It is simply removing anything. NgFor is the other structural directive which is used to render elements or components on the page based on the contents of an iterable or simple an array. Let’s look at an example. Consider the following array of JSON data inside a component class. policies: [] = [ {id: 0, name: "policy001"}, {id: 2, name: "policy002"}, {id: 3, name: "policy003"}, {id: 4, name: "policy004"}, {id: 5, name: "policy005"}, ];To render the data from the array, we can use ngFor as shown in the HTML template code below. <table> <thead> <th># Policy ID</th> <th>Policy name</th> </thead> <tbody> <TR *ngFor="let policy of policies"> <td>{{policy.id}}</td> <td>{{policy.name}}</td> </tr> </tbody> </table>For each element in the array - policies, the HTML <tr> is rendered in the page. We can use the temporary object “policy” to access the data inside the object (one at a time) during the iteration. If you are coming from a C# background, you can think of ngFor like a for-each loop. Note: The let and of keywords are mandatory in the ngFor expression. |
|