I want to create an ErrorComponent responsible to display any error message for the entire application on the top of the page. So, naturally I was wondering about something like:
<my-app>
<error-app></error-app>
<!-- Other stuff -->
</my-app>
I have a Pluker website which illustrate the problem: http://plnkr.co/edit/wYy4gl
I want to be able to add an error from anywhere calling the ErrorComponent. As in:
// File app/app.component.ts
onSelect(hero: Hero) {
this.selectedHero = hero;
this.errorComp.addError(hero.name);
}
The alert shows the errors being added to errors
:
// File app/error-app.component.ts
addError(e:string) {
this.errors.push(e);
alert("Errors:" + this.errors + "| AddeError: " + e);
}
But the list {{errors}}
is not being updated by some reason:
// File app/error-app.component.ts
<li>{{errors}}</li>
Any help is appreciated.
答案 0 :(得分:2)
Instead of <li>{{errors}}</li>
try this:
<li *ngFor="let error of errors">{{error}}</li>
Also, you referenced your error component in the wrong way. Instead of injecting it via DI you should use @ViewChild, like so:
import { Component, ViewChild } from '@angular/core';
// ....
@Component({
selector: 'my-app',
directives: [ ErrorAppComponent],
//providers: [ErrorAppComponent ],
template: `
<h2>Error list</h2>
<error-app #error></error-app>
<hr>
<h2>Click bellow to add to the error list</h2>
<ul class="heroes">
<li *ngFor="let hero of heroes"
[class.selected]="hero === selectedHero"
(click)="onSelect(hero)">
<span class="badge"></span> {{hero.name}}
</li>
</ul>
`
})
export class AppComponent {
constructor() { }
title = 'Tour of Heroes';
heroes = HEROES;
selectedHero: Hero;
@ViewChild("error") errorComp;
onSelect(hero: Hero) {
this.selectedHero = hero;
this.errorComp.addError(hero.name);
}
}