Assigning TypeScript property values with = vs :

Viewed 173

I have the following Angular component:

@Component({
  ...
  template: `
  <div>{{getDisplayValue(value)}}</div>
  <button (click)="value= { display: 'one' }">1</button>
  <button (click)="value.display = 'two'">2</button>`
})
export class TestProblemButtonClickComponent implements OnInit {

  public value = {display: 'old'};

  public getDisplayValue(value): string {
    return value.display;
  }

  ...
}

Why is an = used after declaring the public value property? I'm used to seeing properties followed by a :, then the value. If I change the = to a :, I get some errors when I click button 2. If go into the value property's object and change the : after dislay to a =, the code doesn't even run and I get the following error: Did you mean to use a ':'? An '=' can only follow a property name when the containing object literal is part of a destructuring pattern.

Can someone talk me through this?

1 Answers

You seem to be confused between:

  • JavaScript class member assignation (public value = something)
  • JS object key value assignation ({display: 'old'})
  • TypeScript variable type declaration (public value: valueType)
  • JavaScript "{display = 'old'}" means nothing, except in the context of a function argument destructuring with default value
Related