Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom template rendering with *ngFor

Tags:

angular

ngfor

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.

like image 967
Sven Bardos Avatar asked Jul 24 '16 13:07

Sven Bardos


People also ask

Why * is used in ngFor?

The * character before ngFor creates a parent template. It's a shortcut to the following syntax: template=“ngFor let item of items” .

How do you use ngFor in a tag?

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.

What is ngForOf?

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.

How can I improve my ngFor performance?

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.


1 Answers

@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>
like image 94
Günter Zöchbauer Avatar answered Sep 29 '22 12:09

Günter Zöchbauer