Search code examples
angulartypescriptngmodel

Dynamic value for ngModel


Can I put function as value somehow for ngModel? I want to set the value later for my input (so I expect, when I change the entity value, the model to be updated), that's why I want to check before if it exists or not, hence the function. I have the following and it's not working:

@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] : ''
    }
};

Solution

  • You can't pass a function to [(ngModel)] but you can split the binding and do the checks in the binding like

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