typescript - Liên kết không hoạt động trong mẫu Angular2
errorType không hiển thị khi gọi với Alert.showAlert("success","someMsg"); từ một Component khác nhưng nó hoạt động khi khởi tạo ngay tại khai báo của chính errorType.
thành phần :
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;
}
}
mẫu :
<div id="messageAlert" >
<strong>{{errorType}}:</strong> this is the error message at top of the page
</div>
Thực sự trân trọng sự giúp đỡ của bạn trong việc giải quyết vấn đề này khi giá trị errrorType không được liên kết với erroType
Câu trả lời #1
Đó là vì bạn sử dụng các trường tĩnh. Khi sử dụng {{errorType}}, một thuộc tính không tĩnh của thành phần được sử dụng.
Tôi sẽ tái cấu trúc thành phần của bạn theo cách này:
import {Component} from 'angular2/core';
@Component({
selector: 'alert-component',
templateUrl: 'app/alert.template.html'
})
export class Alert {
public errorType:string;
public messageAlrt:string;
}
Khi bạn muốn hiển thị cảnh báo của mình, tôi sẽ thêm nó một cách động:
@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;
}
);
}
Hãy xem câu trả lời tuyệt vời này từ Günter:
- Các tab động Angular 2 với các thành phần do người dùng chọn bằng cách nhấp
