【问题标题】:Binding is not working in Angular2 template绑定在 Angular2 模板中不起作用
【发布时间】:2016-10-02 12:48:50
【问题描述】:

从另一个 Component 调用 Alert.showAlert("success","someMsg"); 时,errorType 不显示,但在 errorType 本身的声明处初始化时它正在工作。

组件:

 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;
        }

    }

模板:

<div id="messageAlert" >
            <strong>{{errorType}}:</strong> this is the error message at top of the page      
        </div>

非常感谢您帮助解决这个 errrorType 值未绑定到 erroType 的问题

【问题讨论】:

  • 你能分享你调用showAlert函数的代码吗

标签: data-binding typescript angular


【解决方案1】:

这是因为您使用静态字段。使用{{errorType}}时,使用了组件的非静态属性。

我会这样重构你的组件:

import {Component} from 'angular2/core';

@Component({
    selector: 'alert-component',
    templateUrl: 'app/alert.template.html'
})
export class Alert {
  public errorType:string;
  public messageAlrt:string;
}

当你想显示你的警报时,我会动态添加它:

@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;
      }
    );
  }

看看这个伟大的君特的回答:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-14
    • 1970-01-01
    • 2019-05-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多