Let's talk more about Angular 18.
So you want to iterate through an array in Angular to use repeating sections on your UI. Right? Well, Angular supplies a directive called *ngFor, which essentially creates a for loop on your page.
Let's say you're generating menu items dynamically on your page. You could hard-code them in the HTML, but if there's any chance the menu items may change in some way, you're asking for trouble. Besides, even HTML code should be as reusable as we can make it, right?\
Let's create a custom component whose sole purpose in life is to display a menu of hyperlinks.
Step 1.
Once you've generated your shiny new component, you'll need to import *ngFor, since it isn't in the Angular core. Add this line:
import { CommonModule } from '@angular/common';
Be sure to include CommonModule in your imports array as well:
imports: [CommonModule],
So far, so good.
Step 2.
Now, we need a data source. Let's create an array that has a few section headers along with the name of the sections on this page we'll be navigating to.
{id: 1, name: 'About', url: '#section1'},
{id: 2, name: 'Projects', url: '#section2'},
{id: 3, name: 'Experience', url: '#section3'},
{id: 4, name: 'Education', url: '#section4'},
{id: 5, name: 'Publications', url: '#section5'},
{id: 6, name: 'Press', url: '#section6'},
{id: 7, name: 'Blog', url: '#section7'}
];
No comments:
Post a Comment