[英]Angular passing data to child component
嘿,如果登錄失敗,我正在嘗試在我的登錄頁面上顯示一條簡單的錯誤消息。 以下是我的login.component.html:
<div class="container shadow login-container">
<div class="row">
<div class="col-sm-12 text-center">
<div class="error-message">
<app-server-error [errorMessage]="error" ></app-server-error> -----> not displaying on screen
</div>
<div class="login-form-container">
<div class="login-input-container">
<input [(ngModel)]="user.email" type="email" placeholder="Enter your email" class="buddha-input"/>
</div>
<div class="login-input-container">
<input [(ngModel)]="user.password" type="password" placeholder="Enter password" class="buddha-input"/>
</div>
<div class="login-input-container">
<button (click)="tryLogin()" class="login-form-button">Login</button>
</div>
</div>
</div>
</div>
</div>
以下是我的server-error.component.html:
<p>
{{errorMessage}}
</p>
以下是我的server-error.component.ts
import { Component, OnInit, Input } from '@angular/core';
@Component({
selector: 'app-server-error',
templateUrl: './server-error.component.html',
styleUrls: ['./server-error.component.css']
})
export class ServerErrorComponent implements OnInit {
@Input() public errorMessage: string;
constructor() { }
ngOnInit() {
}
}
“錯誤”沒有出現在屏幕上,我也沒有在控制台上收到錯誤。 請讓我知道如何解決這個問題? 謝謝
使用[errorMessage]="error"
,錯誤應該是一個變量。
所以你需要在你的組件中定義它。
但是如果你想顯示字符串"error"
,
然后像這樣傳遞它[errorMessage]="'error'"
或errorMessage="error"
@Input() public errorMessage: string;
期望error
是一個字符串。
像這樣在 in.ts 中定義error
error = 'error message'
另一個發布的答案可能會解決您的問題,但我會使用 go 服務,該服務將負責在應用程序中的任何地方顯示錯誤,並且您可以完全控制錯誤組件,因為它集中在一個地方:
錯誤服務:
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable()
export class ErrorService {
constructor() { }
private errorMessages = new BehaviorSubject('');
errorMessage = this.errorMessages.asObservable();
showError(message: string) {
this.errorMessages.next(message)
}
}
Error.Component.ts:
import { Component, OnInit, Input } from '@angular/core';
import {ErrorService } from "../error.service";
@Component({
selector: 'app-server-error',
templateUrl: './server-error.component.html',
styleUrls: ['./server-error.component.css']
})
export class ServerErrorComponent implements OnInit {
private errorMessage : any;
constructor(public errorService : ErrorService) { }
ngOnInit() {
this.errorService.errorMessage.subscribe(value => {
this.errorMessage = value;
})
}
}
App.Component.html:
// show it in app.component
<div class="error-message">
<app-server-error></app-server-error>
</div>
使用(在登錄組件中):
import { Component, OnInit } from "@angular/core";
import {ErrorService } from "../error.service";
@Component({
selector: "app-login",
templateUrl: "./login.component.html",
styleUrls: ["./login.component.css"]
})
export class LoginComponent implements OnInit {
constructor(public errorService: ErrorService) {}
user = {};
ngOnInit() {}
tryLogin(){
this.errorService.showError('An error');
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.