typescript - La vinculación no funciona en la plantilla de Angular2
errorType no se muestra al llamar con Alert.showAlert("success","someMsg"); desde otro Component, pero funciona al inicializarse en la declaración de errorType mismo.
componente :
import {Component} from 'angular2/core';
@Component({
selector: 'alert-component',
templateUrl: 'app/alert.template.html'
})
export class Alert {
public static errorType:string;
public static messageAlrt:string;
public static showAlert(type:string, message:string): void{
Alert.errorType=type;
}
}
plantilla :
<div id="messageAlert" >
<strong>{{errorType}}:</strong> this is the error message at top of the page
</div>
Realmente aprecio tu ayuda para resolver este problema en el que el valor de errorType no se está vinculando a erroType
Respuesta #1
Es porque utilizas campos estáticos. Al usar {{errorType}}, se utiliza una propiedad no estática del componente.
Refactorizaría tu componente de esta manera:
import {Component} from 'angular2/core';
@Component({
selector: 'alert-component',
templateUrl: 'app/alert.template.html'
})
export class Alert {
public errorType:string;
public messageAlrt:string;
}
Cuando quieras mostrar tu alerta, yo la añadiría dinámicamente:
@Component({
(...)
template: `<div #target></div>`
})
export class SomeComponent {
@ViewChild('target', {read: ViewContainerRef}) target;
showAlert(type:string, message:string) {
this.resolver.resolveComponent(Alert).then(
(factory:ComponentFactory<any>) => {
this.cmpRef = this.target.createComponent(factory);
this.cmpRef.type = type;
}
);
}
Mira esta gran respuesta de Günter:
- Pestañas dinámicas en Angular 2 con componentes elegidos por el usuario al hacer clic
