ngModel的动态值

时间:2017-01-27 10:22:07

标签: angular typescript ngmodel

我可以以某种方式将函数作为值ngModel吗?我想稍后为我的输入设置值(所以我希望,当我更改entity值时,要更新的模型),这就是为什么我要检查之前是否存在,因此函数。我有以下内容,但它不起作用:

@Component({
    selector: 'string-editor',
    template: `
    <dl>
      <dt>{{propertyName}}</dt>
      <dd>
        <input
          type="text"  
          [(ngModel)]="getValue()" />
      </dd>
    </dl>`,
})
export class StringEditor {

    @Input()  public propertyName: string;
    @Input()  public entity: any;

    getValue() {
      return this.entity ? this.entity[this.propertyName] : ''
    }
};

2 个答案:

答案 0 :(得分:1)

您无法将函数传递给[(ngModel)],但您可以拆分绑定并在绑定中执行检查,如

<input
  [ngModel]="entity ? entity[propertyName] : null"
  (ngModelChange)="entity && propertyName ? entity[propertyname] = $event: null"

答案 1 :(得分:-1)

不建议在绑定中使用功能。你还能做什么,

[(ngModel)]="someValue"             //<<===changed



export class StringEditor {

    @Input()  public propertyName: string;
    @Input()  public entity: any;

    ngOnInit(){                     //<<<===added
       this.someValue=this.entity ? this.entity[this.propertyName] : ''
    }
};