如何预选自动完成功能?

时间:2018-08-24 08:50:42

标签: angular typescript autocomplete angular-material

我需要一个选项来预先选择一个带有值的自动完成功能,但之后仍然可以更改自动完成功能。这可能吗?我已经尝试在input元素上使用value属性,但这不起作用。

userlist.component.html

<mat-form-field>
    <input type="text" placeholder="Name" aria-label="Name" matInput [formControl]="myControl" [matAutocomplete]="auto">
        <mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn.bind(this)" (optionSelected)="output($event.option.value)">
            <mat-option *ngFor="let option of filteredOptions | async" [value]="option">
                {{option.display_name}}
            </mat-option>
        </mat-autocomplete>
</mat-form-field>

userlist.component.ts

export class AutoUserlistComponent implements OnInit {

    myControl = new FormControl();
    options;
    filteredOptions: Observable<any[]>;
    @Output() change = new EventEmitter<any>();

    constructor(
        private loaderService: LoaderService
    ) { }

    ngOnInit() {
        this.options = this.loaderService.getUser();
        this.filteredOptions = this.myControl.valueChanges
        .pipe(
            startWith(''),
            map(name => name ? this._filter(name) : this.options.slice())
        );
    }

    displayFn(user): string | undefined {
            return user ? user.first_name + ' ' + user.last_name  : undefined;
    }

    private _filter(name: string) {
        return this.options.filter(user => {
            const searchStr = user.display_name.toLowerCase() + user.ad_login.toLowerCase();
            return searchStr.indexOf(name.toLowerCase()) !== -1;
        });
    }

    output(user) {
        this.change.emit(user);
    }
}

1 个答案:

答案 0 :(得分:-1)

我有适合您的样品。

组件:

#participantInput="ngModel"

模板:

@ViewChild('participantInput') participantInput: ElementRef;

我希望代码可以帮助您!