Praveenks
Praveenks

Reputation: 1496

Not able to pass values from Parent to child in Angular

I am trying to write a very simple program of passing value from parent to child component. In the below code, I am trying to print firstName(John) but as shown in the screenshot, it's not getting printed.

app.component.ts

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  firstName = "John";
}

app.component.html

<app-cards>
  [firstName]="firstName"
</app-cards>

card.component.ts

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

@Component({
  selector: 'app-cards',
  templateUrl: './cards.component.html',
  styleUrls: ['./cards.component.css']
})
export class CardsComponent implements OnInit {
  @Input() firstName : string | undefined;

  constructor() { }

  ngOnInit(): void {
  }

}

card.component.html

<div>
    First Name: {{ firstName }}
</div>

Output :

enter image description here

Upvotes: 1

Views: 32

Answers (1)

Jason White
Jason White

Reputation: 5843

Your app.component.html file is wrong. You have [firstName] between the <app-cards> element tags instead of having it as an attribute.

app.component.html

<app-cards
  [firstName]="firstName">
</app-cards>

Upvotes: 1

Related Questions