I have a History component which holds an array of HistoryEntries
.
HistoryComponent
looks like:
@Component({
selector: 'history',
template: `
<div>
<historyEntry *ngFor='let entry of historyentries'></historyEntry>
</div> `,
directives : [HistoryEntryComponent]
})
The HistoryComponent-class looks like:
export class HistoryComponent{
public historyentries = [
new HistoryEntryComponent(1, "lalala"),
new HistoryEntryComponent(2, "xxxxx")
];
}
Then I have a HistoryEntryComponent:
@Component({
selector: 'historyentry',
template: `
<div>
<h1>ID: {{Id}} , Descr.: {{Description}}</h1>
</div>
`
})
and a class:
export class HistoryEntryComponent {
constructor(public Id : Number, public Description : string)
{}
}
If I render that, nothings shows up. I have already used a <li>
to display the id and description, which works like expected. But of course HistoryEntry
itself could get very complicated and need its own logic etc. So there must be a way to render <historyentry>
as given by a template, isn't it?
In WPF I would say HistoryEntry
is a UserControl
with its own ViewModel
attached.
The * character before ngFor creates a parent template. It's a shortcut to the following syntax: template=“ngFor let item of items” .
How to use the ngFor directive? The ngFor directive does create the HTML-Element it is placed in as many times as there are elements in the array. So to create a list-element for each array element, we place the ngFor directive inside of the li tag.
The ngForOf directive is generally used in the shorthand form *ngFor . In this form, the template to be rendered for each iteration is the content of an anchor element containing the directive. The following example shows the shorthand syntax with some options, contained in an <li> element.
The user will add a new movie, delete a movie, sort the list in a different order, or simply refresh the movie from the back end. This will force the angular to render the template again. The easiest way to achieve that is to remove the entire list and render the DOM again.
@Component({
selector: 'history',
template: `
<div>
<historyentry *ngFor='let entry of historyentries' [entry]="entry"></historyentry>
</div> `,
directives : [HistoryEntryComponent]
})
export class HistoryEntryComponent {
@Input() entry:HistoryEntry; // or whatever type `entry` is
constructor()
{}
}
<h1>ID: {{entry?.Id}} , Descr.: {{entry?.Description}}</h1>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With