简体   繁体   English

将变量从父组件传递给子组件

[英]Pass variable from parent component to child component

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 传递给 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 class="text-sm font-medium text-red-700">{{ title }}</p>
<p class="mt-1 text-sm text-gray-500">{{ 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;

There are few errors in your code.您的代码中几乎没有错误。

LoginComponent登录组件

  1. The ErrorTitle and ErrorMessage should be placed in ErrorComponent but not LoginComponent . ErrorTitleErrorMessage应该放在ErrorComponent而不是LoginComponent中。 With existing code, you are expecting that your LoginComponent to received the mentioned parameters as:使用现有代码,您期望LoginComponent收到上述参数:
<app-login [ErrorTitle]="/* title */" [ErrorMessage]="/* message */"></app-login>
  1. Assign value to title and message variables should use = operator , : is for specifying the type.titlemessage变量赋值应该使用=运算符:用于指定类型。
export class LoginComponent  {
  title = 'Incorrect credentials';
  message = 'This password do not match any credentials';
}

ErrorComponent错误组件

  1. Add ** ErrorTitle and ErrorMessage input parameter.添加 ** ErrorTitleErrorMessage输入参数。
export class ErrorComponent implements OnInit {

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

The HTML template for ErrorComponent should be: ErrorComponent的 HTML 模板应该是:

<p class="text-sm font-medium text-red-700">{{ ErrorTitle }}</p>
<p class="mt-1 text-sm text-gray-500">{{ ErrorMessage }}</p>

Sample StackBlitz Demo 示例 StackBlitz 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM