Angular lesson 3: pass data from parent component to child with input binding

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';
  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 />
  {{myContent}} Room {{}}

  School Name: {{Name}}

  Number of students: {{room.students.length}}

<p *ngFor="let student of room.students">
  Studen Name: {{}}

File app.component.ts

import {Component} from '@angular/core';
import { rooms } from './school';
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
export class AppComponent{
  title = '';
  name = 'World';
  Rooms = rooms;

File app.component.html

<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>

angular lesson 3

Leave a Reply