将变量从 parent 组件传递到 child 组件

Pass variable from parent component to child component

我真的不知道我做错了什么。

我正在尝试将错误标题和消息从 LoginComponent 传递到 ErrorComponent。

登录组件:

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>

错误组件:

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

它向我显示了这个错误:

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

因此,如果我在不给它们赋值的情况下声明它们,它不会显示错误,而是空白。

 title: string;
 message: string;

您的代码中几乎没有错误。

LoginComponent

  1. ErrorTitleErrorMessage 应该放在 ErrorComponent 而不是 LoginComponent。使用现有代码,您希望 LoginComponent 收到上述参数:
<app-login [ErrorTitle]="/* title */" [ErrorMessage]="/* message */"></app-login>
  1. titlemessage变量赋值应该使用=运算符:用于指定类型。
export class LoginComponent  {
  title = 'Incorrect credentials';
  message = 'This password do not match any credentials';
}

ErrorComponent

  1. 添加 **ErrorTitleErrorMessage 输入参数。
export class ErrorComponent implements OnInit {

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

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