Binding 'this' in Angular Material Autocomplete displayWith using Angular 5

前端 未结 5 750
借酒劲吻你
借酒劲吻你 2021-01-04 10:50

I was trying to use the Material Angular autocomplete and I came across the displayWith function which can be apparently used to be the output that is displayed on selection

相关标签:
5条回答
  • 2021-01-04 11:20

    You just missed an undefined check before using attribute.

    <mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn" (optionSelected)="optionSelected($event)">
    
    <mat-option *ngFor="let user of users" [value]="user" >
        {{ user.first_name }} {{ user.last_name }}
    </mat-option>
    
    displayFn(user) {
        if (!user) return '';
        return user.name;
    }   
    
    0 讨论(0)
  • 2021-01-04 11:28
    displayFn = value => {
      // now you have access to 'this' 
      this.someMethod();
      return 'formatted display';
    }
    
    0 讨论(0)
  • 2021-01-04 11:32

    Define cThis = this as a property of your class, and then use it inside your displayFn function:

    <mat-autocomplete #autoOutlet="matAutocomplete" [displayWith]="displayFn(id, cThis)">


    cThis = this;
    displayFn(id, cThis) {
     return cThis.getValue(id)
    }
    getValue(id) {
     /**return some string
    }
    

    Demo that shows binding in displayWith

    0 讨论(0)
  • 2021-01-04 11:37

    You could just change your template to be

    <mat-autocomplete #autoOutlet="matAutocomplete" [displayWith]="displayFn(id, this)">
    

    Inside of templates this is a reference to your Component. Then just change your function to

    displayFn(id, _this) {
      return _this.getValue(id)
    }
    

    If [displayWith] needs to be a function, you could create a property that returns your displayFn like this:

    get createDisplayFn() {
      return (id) => {
        return this.getValue(id)
      }
    }
    

    and change your binding to [displayWith]="createDisplayFn". As ES6 arrow function can't be rebinded, this should still be a reference to your component.

    0 讨论(0)
  • 2021-01-04 11:38

    It is because of this is not binding to the component and its binding to mat-select option

    NOw for using component's function, you have to use arrow function, the preferable method or pass this from the HTML function

    I will use the arrow function to use the component's function

    Without arrow function

    displayFn(data: any) {
        return data.Id?this.sometask(data):''
    }
    

    With arrow function

    displayFn = (data: any) => {
        return data.Id?this.sometask(data):''
    }
    

    This work in my scenario and it worked in your scenario too.

    0 讨论(0)
提交回复
热议问题