In lesson 2, we learnt about Component. Now, we continue learn about component.
Step 1:
Create file school.ts in src/app
interface Student{ name: string; } export interface Room{ name: string; students: Student[]; } export let rooms: Room[] = [ {name: "1",students: [{name: "Adam"},{name: "Eva"}]}, {name: "2",students: [{name: "Steven"},{name: "Louis"}]} ];
Step 2: edit some files
file my-component.component.ts
import {Component, Input, OnInit} from '@angular/core'; import {Room} from '../school'; @Component({ selector: 'app-my-component', templateUrl: './my-component.component.html', styleUrls: ['./my-component.component.css'] }) export class MyComponentComponent implements OnInit { @Input('name') Name: string; @Input() room: Room; myContent = "Welcome to"; constructor() { } ngOnInit() { } }
MyComponentComponent has two input properties, typically adorned with @Input decorations.
The first @Input aliases the child component property name Name as ‘name’.
file my-component.component.html
<hr /> <p> {{myContent}} Room {{room.name}} </p> <p> School Name: {{Name}} </p> <p> Number of students: {{room.students.length}} </p> <p *ngFor="let student of room.students"> Studen Name: {{student.name}} </p>
File app.component.ts
import {Component} from '@angular/core'; import { rooms } from './school'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent{ title = 'Www.Tutorialspots.com'; name = 'World'; Rooms = rooms; }
File app.component.html
<h1> {{title}} </h1> <div>Hello {{name}}!</div> <div>Number of rooms: {{Rooms.length}}</div> <app-my-component *ngFor="let room of Rooms" [name]="name" [room]="room"></app-my-component>