使用 = vs 分配 TypeScript 属性 值:

Assigning TypeScript property values with = vs :

我有以下 Angular 组件:

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

  ...
}

为什么在声明 public value 属性 之后使用 =?我习惯于看到属性后跟 :,然后是值。如果我将 = 更改为 :,单击按钮 2 时会出现一些错误。如果进入 value 属性 的对象并更改 :dislay= 之后,代码甚至没有 运行,我得到以下错误:Did you mean to use a ':'? An '=' can only follow a property name when the containing object literal is part of a destructuring pattern.

有人可以帮我解决这个问题吗?

你似乎混淆了:

  • JavaScriptclass成员分配(public value = something)
  • JS对象键值赋值({display: 'old'})
  • TypeScript 变量类型声明(public value: valueType)
  • JavaScript "{display = 'old'}" 没有任何意义,除非在函数参数解构的上下文中使用默认值