Angular Material Autocomplete using template driven form error,数据不会显示

Angular Material Autocomplete using template driven form error, data won't show

提问人:Rafi Irvansyah 提问时间:10/19/2023 更新时间:10/19/2023 访问量:18

问:

因此,在独立组件内的 angular 材料中实现过滤器自动完成存在问题。但是,我没有使用表单控制,而是使用模板驱动表单([ngModel])。实际上,数据已经显示在控制台中,但在自动完成显示中,数据不会显示。我已经调试了一天,但我已经不知所措了,因为似乎我整天都呆在这里。我希望你们能帮助我。

下面是我的模板代码。

<div class="flex flex-col mb-[12px]">
      <label for="user.report_to_user" class="text-[10px] font-normal">*Report To User</label>
      <input 
            [(ngModel)]="formData.data.reportToUser" 
            (ngModelChange)="onInputChange()" 
            type="text" 
            name="user.report_to_user" 
            placeholder="Report To User" 
            class="input-form" 
            [matAutocomplete]="auto" 
            required>
            <mat-autocomplete #auto="matAutocomplete" [displayWith]="displayOption">
               <option *ngFor="let option of filteredOptions" [value]="option">
                  {{ option.desc }}
               </option>
            </mat-autocomplete>
            <div 
                *ngIf="formData.data.reportToUser == ''" 
                class="text-[10px] text-red-600 justify-start">
                    {{ requiredValidation }}
            </div>
</div>

这是我的组件代码。

import {MatAutocompleteModule} from '@angular/material/autocomplete';
import {MatAccordion, MatExpansionModule} from '@angular/material/expansion';
import {MatIcon, MatIconModule} from '@angular/material/icon';
import {map, startWith} from 'rxjs/operators';
import {FormsModule, FormControl, ReactiveFormsModule} from '@angular/forms';
import {AuthService} from '../../../../services/user-management/auth/auth.service';
import {Observable} from 'rxjs';

export interface UserLookUpResponse {
    data: UserLookUp[];
    IsSuccess: boolean;
    Message: string;
    IsApproval: boolean;
    ReturnId: number;
}

export interface UserLookUp {
    id: string,
    desc: string
}

@Component({
    selector: 'app-create-user-form',
    standalone: true,
    imports: [
        CommonModule,
        MatDialogModule,
        MatExpansionModule,
        MatIconModule,
        FormsModule,
        MatAutocompleteModule,
        ReactiveFormsModule
    ],
    templateUrl: './create-user-form.component.html',
    styleUrls: ['./create-user-form.component.css']
})
export class CreateUserFormComponent implements OnInit {
    constructor(
        private ref : MatDialogRef<CreateUserFormComponent>,
        private authService : AuthService
    ) {}

    options: UserLookUp[] = [];
    filteredOptions: UserLookUp[] = this.options;

    ngOnInit(): void {
        this.fetchUserLookUp();
    }

    onInputChange() {
        const value = this
            .formData
            .data
            .reportToUser
            .toLowerCase();
        console.log(value);
        this.filteredOptions = this
            .options
            .filter(option => option['desc'].toLowerCase().includes(value));
        console.log(this.filteredOptions);
    }

    formData = {
        data: {
            userInfo: {
                username: '',
                first_name: '',
                last_name: '',
                email: '',
                password: '',
                job_title: '',
                is_user_active: true,
                is_user_locked: false,
                department: '',
                office_address: '',
                office_country: ''
            },
            reportToUser: '',
            reportToTeam: 'Default'
        }
    };

    randomPass: string = '';
    showGeneratedPassword: boolean = false;
    passwordError: string = '';
    isButtonDisabled: boolean = false;
    requiredValidation: string = 'This field is required' @ViewChild(MatAccordion)accordion !: MatAccordion;

    closePopup() {
        this
            .ref
            .close('Closed using function')
    };

    onSelectChange(event : Event): void {
        const target = event.target as HTMLSelectElement;
        const selectedValue = target.value;

        if (selectedValue === 'generate') {
            this.generatePassword();
        } else {
            this.randomPass = '';
            this.showGeneratedPassword = false;
        }
    };

    fetchUserLookUp() {
        this
            .authService
            .getLookUpUser()
            .subscribe((user) => {
                this.options = user.data;
                console.log('Options:', this.options);
            })
    }

    displayOption(option : UserLookUp) {
        console.log("ini yang di display", option);
        return option
            ? option.desc
            : 'undefined';
    }

这是我的服务代码,用于获取分离文件中的数据,auth.service.ts

getLookUpUser(): Observable<any> {
    let token = this.utils.getToken()
      const httpOptions = {
        headers: new HttpHeaders({
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        })
      };
    return this.http.get(`${this.apiUrl}/User/GetUserLookup`, httpOptions)
  }

我需要你们的帮助,谢谢!

我已经尝试更改 displayOption,并且我已经尝试在 angular 材质文档中完成他们所说的一切,但似乎我没有得到任何启示。

调试 错误处理 Angular-Material 自动完成

评论


答: 暂无答案