简体   繁体   English

角度材质:在下拉列表中获取所选值的ID

[英]Angular material: get the id of the chosen value in a dropdown

I have a material dialog that opens from an edit button on a table of data. 我有一个材质对话框,该对话框从数据表上的编辑按钮打开。

I am getting undefined on "ressursId" that should get it's value from the patchValue method but that always is undefined too. 我在“ ressursId”上未定义,应该从patchValue方法获取其值,但始终也未定义。

There seems to be an issue with calling pathcValue() and using [displayWith]="displayFn" at the same time, as the displayWith overwrites the patchValue? 调用pathcValue() 并同时使用 [displayWith]="displayFn"似乎有问题,因为displayWith会覆盖patchValue? I'm not sure. 我不确定。

So what is not working here is that when I type in the input even though I get filtered results in the dropdown, I should be displaying the initial value from the table (if one exists, it doesn't always exist when the dialog is opened). 所以在这里行不通的是,即使我在下拉列表中得到过滤的结果,当我输入输入时,我仍应显示表中的初始值(如果存在,则在打开对话框时并不总是存在) )。

I also more importantly need to get the ressursId of the chosen value because without it, I cannot make the PUT request to update the data. 更重要的是,我还需要获取所选值的ressursId ,因为没有它,我将无法发出PUT请求以更新数据。

What am I doing wrong? 我究竟做错了什么? The Angular docs are too simplistic! Angular文档太简单了!

Partial form component.html 部分表格component.html

   <form class="mat-dialog-content" (ngSubmit)="submit()" #formControl="ngForm" [formGroup]="patchForm">

      <div class="form">
          <mat-form-field>
            <input
              matInput
              formControlName="selectedRessurs"
              [matAutocomplete]="auto"
              placeholder="Ressurs"
              [formControl]="ressursControl"
              >
            <mat-autocomplete #auto="matAutocomplete" name="selectedRessurs" [displayWith]="displayFn">
              <mat-option *ngFor="let option of filteredOptions | async" [value]="option">
               {{ option.navn }}
              </mat-option>
            </mat-autocomplete>
          </mat-form-field>
      </div>

and my component.ts 和我的component.ts

export class PatchDialogComponent implements OnInit {

  functiongGroup: FunksjonsGruppe;
  ressurs: Ressurser;

  @Input() prosjektFunksjon: ProsjektFunksjon;
  @Input() ressurser: Ressurser[];
  @Input() prosjFunk: ProsjektFunksjon[];

  // selectedFunksjon: any;
  selectedRessurs: number;
  selectedRessursId: number;
  ressursId: number;
  prosjektId: number;
  selectedRowId: any;
  funksjonsgruppe: any;
  fetchedProsjektFunksjon: ProsjektFunksjon;

  constructor(public dialogRef: MatDialogRef<PatchDialogComponent>,
              private projectService: ProjectService,
              @Inject(MAT_DIALOG_DATA) public data: any
              ) {
              }

  formControl = new FormControl('', [
    // Validators.required
    // Validators.email,
  ]);
  ressursControl = new FormControl();
  // options: Ressurser[];
  filteredOptions: Observable<Ressurser[]>;

  patchForm = new FormGroup({
    selectedRessurs: new FormControl(),
    rollenavn: new FormControl(),
    estimertAntallTimer: new FormControl()
  });

  getErrorMessage() {
    return this.formControl.hasError('required') ? 'Required field' :
      this.formControl.hasError('email') ? 'Not a valid email' :
        '';
  }

  submit() {
    // empty stuff
  }

  onNoClick(): void {
    this.dialogRef.close();
  }

  public confirmPut(): void {
    console.log(' 99: ', this.data);
    this.prosjektFunksjon = {
        prosjektFunksjonId: this.fetchedProsjektFunksjon.prosjektFunksjonId,
        estimertAntallTimer: this.patchForm.value['estimertAntallTimer'],
        rollenavn: this.patchForm.value['rollenavn'],
        funksjonId: null,
        funksjonNavn: null,
        subGruppe: null,
        subGruppeId: null,
        gruppe: null,
        gruppeId: null,
        ressursId: this.patchForm.value.selectedRessurs['ressursId'],
        ressursNavn: null
    };
    console.log('data 101: ', this.data, '\n', ' ProsjektFunksjonsID: ', this.fetchedProsjektFunksjon.prosjektFunksjonId, '\n', ' prosjektFunksjon: ',  this.prosjektFunksjon, );
    this.projectService.updateProjectFunction(this.prosjektId, this.selectedRowId, this.prosjektFunksjon).subscribe();
  }

  displayFn(user?: Ressurser): string | undefined {
    return user ? user.navn : '';
  }

  private _filter(navn: string): Ressurser[] {
    const filterValue = navn.toLowerCase();
    return this.ressurser.filter(option => option.navn.toLowerCase().indexOf(filterValue) === 0);
    // return this.ressurser.filter(option => option.ressursId.indexOf(filterValue) === 0);
  }

  ngOnInit(): void {
    this.data = this.dialogRef.componentInstance;
        this.projectService.getResources().subscribe(r => {
          this.ressurser = r;
          this.ressurser = (this.ressurser || []).sort((a: Ressurser, b: Ressurser) => a.navn.localeCompare(b.navn));
        });

    this.projectService.getProjectFunction(this.prosjektId, this.selectedRowId).subscribe(gpf => {
      // console.log('gpf:  ', gpf);
      this.fetchedProsjektFunksjon = gpf;
      console.log('onit: ', this.fetchedProsjektFunksjon);

      // patchFrom expects an object matching to the formgroup, field by field.
      this.patchForm.patchValue({
        selectedRessurs: this.fetchedProsjektFunksjon['ressursNavn'],
        rollenavn: this.fetchedProsjektFunksjon['rollenavn'],
        estimertAntallTimer: this.fetchedProsjektFunksjon['estimertAntallTimer']
       });
       console.log('After patchValue. fetchedProsjFunk: ', this.fetchedProsjektFunksjon);
    });

    this.filteredOptions = this.ressursControl.valueChanges
      .pipe(
        startWith<string | Ressurser>(''),
        map(value => typeof value === 'string' ? value : value.navn),
        map(navn => navn ? this._filter(navn) : null)
      );

    } // @oninit

}

Sorry, I don't have enough reputation to add a comment yet, but I noticed that you have both a [formGroup]="patchForm" with the formControlName="selectedRessurs" set on your input element, along with a binding to a [FormControl]="ressursControl". 抱歉,我没有足够的声誉来添加评论,但是我注意到您在输入元素上同时设置了[formGroup] =“ patchForm”和formControlName =“ selectedRessurs”,并绑定了[ FormControl] = “ressursControl”。 I would assume that only one of them is valid, most likely the ressursControl. 我假设其中只有一个有效,很可能是ressursControl。 At least it's something to check. 至少这是要检查的东西。

I also found these SO answers to be helpful in understanding FormGroups and FormControls -> What is the difference between formControlName and FormControl? 我还发现这些SO答案有助于理解FormGroups和FormControls-> formControlName和FormControl有什么区别?

Hope this helps! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM