Home > Software design >  Pass variable from parent component to child component
Pass variable from parent component to child component

Time:05-29

I don't really know what I'm doing wrong here.

I'm trying to pass the error title and message from LoginComponent to ErrorComponent.

LoginComponent :

export class LoginComponent  {
  @Input() public  ErrorTitle: string;
  @Input() public   ErrorMessage: string;
  title: 'Incorrect credentials';
  message: 'This password do not match any credentials'
<app-error *ngIf="isError == true" [ErrorTitle]="title" [ErrorMessage]="message"></app-error>

ErrorComponent :

<p >{{ title }}</p>
<p >{{ message }}</p>

It shows me this error :

Property 'title' does not exist on type 'ErrorComponent'

So if I declare them without giving them a value, it doesn't show the error, but it's blank.

 title: string;
 message: string;

CodePudding user response:

There are few errors in your code.

LoginComponent

  1. The ErrorTitle and ErrorMessage should be placed in ErrorComponent but not LoginComponent. With existing code, you are expecting that your LoginComponent to received the mentioned parameters as:
<app-login [ErrorTitle]="/* title */" [ErrorMessage]="/* message */"></app-login>
  1. Assign value to title and message variables should use = operator, : is for specifying the type.
export class LoginComponent  {
  title = 'Incorrect credentials';
  message = 'This password do not match any credentials';
}

ErrorComponent

  1. Add **ErrorTitle and ErrorMessage input parameter.
export class ErrorComponent implements OnInit {

  @Input() ErrorTitle: string;
  @Input() ErrorMessage: string;
}

The HTML template for ErrorComponent should be:

<p >{{ ErrorTitle }}</p>
<p >{{ ErrorMessage }}</p>

Sample StackBlitz Demo

  • Related