【问题标题】:How to set default value for mat-select?如何为 mat-select 设置默认值?
【发布时间】:2020-11-25 15:31:19
【问题描述】:
<mat-select [(ngModel)]='selected' >
   <mat-option *ngFor="let language of languages" [value]="language" >
      {{language}}
   </mat-option >
</mat-select> 

这是我的html

selected:string
constructor(private firestore: AngularFirestore,private globals:GlobalsService) { 
  console.log(this.globals.userUid);
  this.firestore.collection('customers').doc(this.globals.userUid).get().subscribe(function(doc){
    if(doc.exists){
      console.log(doc.data()["language"]);
      this.selected  = doc.data()["language"]
    }
  })
  for (let index = 0; index < avaibleLanguages.length; index++) {
    const language:string = avaibleLanguages[index]
    this.languages.push(language)
  }}

在 console.log 中,我看到我从 firebase 收到了正确的语言,但它没有将其设置为默认选择。这里的所有其他东西都有效

【问题讨论】:

  • 如果把订阅的回调函数改成内联函数,就不会丢失this实例。你需要改变它像.subscribe(doc =&gt; {...})

标签: javascript angular firebase google-cloud-firestore angular-material


【解决方案1】:

只需要将值放入局部变量中。

var local
    this.firestore.collection('customers').doc(this.globals.userUid).get()
    .subscribe(doc =>{
      if(doc.exists){
        local = doc.data()["language"]
      }
    },err => console.log(err),()=>{this.selected = local }
    )
    for (let index = 0; index < avaibleLanguages.length; index++) {
      const language:string = avaibleLanguages[index]
      this.languages.push(language)
    }

【讨论】:

    【解决方案2】:

    如果症状持续存在,请使用 ChangrDetectorRef:在此处查找 https://angular.io/api/core/ChangeDetectorRef

    ...
    constructor (private changeDetector: ChangeDetectorRef) { }
    
    private someFn(): void {
        this.changeDetector.detach();
        this.changeDetector.reattach();
        this.changeDetector.detectChanges();
    }
    ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-04-12
      • 2018-05-15
      • 2022-10-12
      • 1970-01-01
      • 2021-08-15
      • 2018-11-12
      • 1970-01-01
      相关资源
      最近更新 更多