Javascript 角度:Can';单击按钮时不更新类中的属性

Javascript 角度:Can';单击按钮时不更新类中的属性,javascript,angular,Javascript,Angular,在我的类中,我有一个名为“curSelectedSite”的属性,默认设置为null: export class MyComponent implements OnInit { curSelectedSite = null; displayFn(site): string { this.curSelectedSite = site; return site ? site.name : site; } addSite(): void { consol

在我的类中,我有一个名为“curSelectedSite”的属性,默认设置为null:

export class MyComponent implements OnInit {
  curSelectedSite = null;

  displayFn(site): string {
    this.curSelectedSite = site;
    return site ? site.name : site;
  }

  addSite(): void {
      console.warn(this.curSelectedSite) // outputs "null" and not the chosen autocomplete value as it should
  }
}
在我的标记中,我有一个自动完成字段,允许用户从站点列表中选择站点:

<mat-form-field class="field">
    <md-input-container>
        <input type="text" matInput [formControl]="myControl" [matAutocomplete]="auto" placeholder="Choose Site" id="choose-site">
    </md-input-container>
    <mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn">
        <mat-option *ngFor="let site of sites" [value]="site">
            {{site.name}}
        </mat-option>
    </mat-autocomplete>
</mat-form-field>

<button mat-raised-button (click)="addSite()">Add Site</button>

{{site.name}
添加站点

当用户从下拉列表中选择一个选项时,
displayFn
方法触发。如您所见,我正在更新用户选择的
curSelectedSite
属性。但是,当在之后单击“添加站点”按钮时,用户选择了它输出的内容,即原始值,而不是更新后的值。为什么?

您至少需要将自动完成
的值绑定到类属性
curSelectedSite
。如果没有此绑定,Angular无法在用户从自动完成下拉/菜单中选择选项时更新
curSelectedSite
的值

这可以是带有或的表单结构,例如或


{{site.name}
添加站点
{{curseelectedsite}}
这是一个正在实施的计划


希望这有帮助

至少需要将自动完成
的值绑定到类属性
curSelectedSite
。如果没有此绑定,Angular无法在用户从自动完成下拉/菜单中选择选项时更新
curSelectedSite
的值

这可以是带有或的表单结构,例如或


{{site.name}
添加站点
{{curseelectedsite}}
这是一个正在实施的计划


希望这有帮助

当您在displayFn中登录站点时会发生什么情况?您似乎没有向该函数传递任何内容。在
displayFn(site)
的范围之外,如果displayFn的目的是设置
curSelectedSite
,则
curSelectedSite
的值也为空,为什么返回任何内容?
curseelectedsite
没有更新的原因是
displayFn
是一个函数,作为
map autocomplete
的输入参数传递。“自动完成”使用该函数转换显示值。
displayFn
的范围是自动完成组件,而不是您的组件。所以,实际上您正在更新自动完成的
curSelectedSite
component@LLai有道理,谢谢当您在displayFn中登录站点时会发生什么?您似乎没有向该函数传递任何内容。在
displayFn(site)
的范围之外,如果displayFn的目的是设置
curSelectedSite
,则
curSelectedSite
的值也为空,为什么返回任何内容?
curseelectedsite
没有更新的原因是
displayFn
是一个函数,作为
map autocomplete
的输入参数传递。“自动完成”使用该函数转换显示值。
displayFn
的范围是自动完成组件,而不是您的组件。所以,实际上您正在更新自动完成的
curSelectedSite
component@LLai有道理,谢谢
<mat-form-field class="field">
    <md-input-container>
        <input type="text" matInput [formControl]="myControl" [matAutocomplete]="auto" placeholder="Choose Site" id="choose-site" [(ngModel)]="curSelectedSite">
    </md-input-container>
    <mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn">
        <mat-option *ngFor="let site of sites" [value]="site">
            {{site.name}}
        </mat-option>
    </mat-autocomplete>
</mat-form-field>

<button mat-raised-button (click)="addSite()">Add Site</button>

{{curSelectedSite}}