Home Chained Templates in Angular
Reply: 2

Chained Templates in Angular

user1872371
1#
user1872371 Published in 2018-01-11 06:51:34Z

Just learning Angular2/4 so please bear with me...

Assume I have a CoursesComponent which has a list of CourseComponents. The HTMLTemplate for CoursesComponent simply iterates the CourseComponent (list) field and displays each course.

I want the CourseComponent to handle the display of course with it's own HTMLTemplate.

CourseComponent HTMLTemplate (with selector:'course')

<div class='course'>
{{title}}({{code}})
<br/>
{{description}}
</div>

CoursesComponent HTMLTemplate (with selector:'courses')

<div class='courses'>
<ul>
<li *ngFor='let c of courseList'><course></course></li>
</ul>
</div>

AppComponent HTMLTemplate

<div>
<courses></courses>
</div>

How do you achieve this? Is it even possible? Can templates be chained in this fashion?

Imran
2#
Imran Reply to 2018-01-11 07:03:43Z

In your CoursesComponent html file add can add you variable like this

<div class='courses'>
<ul>
  <li *ngFor='let c of courseList'>
    <course [data]="c"></course>
  </li>
</ul>
</div>

Then You have to add a input variable in your CourseComponent ts file

@Input() data: any = [];
Ashraful Islam
3#
Ashraful Islam Reply to 2018-01-11 07:26:29Z

You can try this snippets

course.component.ts

import { Component, Input } from '@angular/core';

@Component({
  selector: 'app-course',
  templateUrl: `
  <h3>Course Title: {{data.title}}</h3>
  <p>Course Description: {{data.description}}</p>
  `,
  styleUrls: ['./course.component.css']
})
export class CourseComponent {
  @Input() data;
}

course-list.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-course-list',
  templateUrl: `
  <ng-container *ngFor="let item of sampleCollection">
      <app-course [data]="item"></app-course>
  </ng-container>
  `,
  styleUrls: ['./course-list.component.css']
})
export class CourseListComponent {

  sampleCollection = [
    {
      title: 'Title Course 1',
      description: 'Description of course 1'
    },
    {
      title: 'Title Course 2',
      description: 'Description of course 2'
    },
    {
      title: 'Title Course 3',
      description: 'Description of course 3'
    }
  ];

}

app.component.html

<app-course-list></app-course-list>
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.32601 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO