Angular - Can't bind to 'ngValue' since it isn't a known property of 'mat-option'

后端 未结 4 1141
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-17 10:23

I\'m using angular 5 and I\'m getting the console error:

Can\'t bind to \'ngValue\' since it isn\'t a known property of \'mat-option\'

4条回答
  •  长发绾君心
    2021-01-17 11:01

    for mat-autocomplete, to use items instead of strings, for mat-option, ngValue wasn't available, however with [value], we can access the object by using option.value instead of option.viewValue:

    allFruits: Item[] = [
        {
          name: 'hello',
          selected: true,
        },
        {
          name: 'world',
          selected: false,
        }
      ];
    
    
    
        
          {{fruit.name}} {{fruit.selected}}
        
      
    
    
    selected(event: MatAutocompleteSelectedEvent): void {
        console.log('selected ', event.option.value); <----- THIS
        console.log('selected ', event.option.viewValue); <---- NOT THIS
    }
    

    with option.value you get the object. With option.viewValue you will get a string representation of the innerHTML that the user sees.

提交回复
热议问题