javascript 访问 Angular Material 表中的输入字段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/52035460/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 09:48:03  来源:igfitidea点击:

Accessing Input fields inside Angular Material table

javascripthtmlangularangular-material

提问by ACristian24

I've been trying for days to get data from input fields inside an Angular Material Table.

几天来,我一直在尝试从 Angular Material Table 内的输入字段中获取数据。

I am basically populating a table with values that come from an API, however whenever we don't get any date, in my case a course doesn't have a scheduled date set, i am inserting a text box where the value should be displayed so the user can set a date for that specific course.

我基本上是用来自 API 的值填充一个表,但是每当我们没有得到任何日期时,在我的情况下,课程没有设置预定日期,我正在插入一个文本框,在那里应该显示值因此用户可以为该特定课程设置日期。

Like this: ExampleNote: Sorry for the censoring, work related names had to be removed.

像这样: 注意:抱歉,必须删除与工作相关的名称。例子

This is my html code:

这是我的 html 代码:

<mat-card>
    <form  #traineeForm="ngForm">
      <mat-form-field>
        <input  readonly matInput type="text" name="name" [ngModel] = "trainee.name"  #name="ngModel">
      </mat-form-field>
      <mat-form-field>
        <input readonly matInput email type="text"  name="email" [ngModel] = "trainee.email" #email="ngModel">
      </mat-form-field>
      <mat-form-field>
        <input readonly matInput type="text"  name="type" [ngModel] = "trainee.type" #type="ngModel">
      </mat-form-field>
      <button mat-raised-button color ="primary" type ="submit">Edit</button>
      <button mat-raised-button color ="warn" type ="submit" (click)="onDelete(trainee.id)">Delete</button>
    </form>
  </mat-card>
<br>
  <mat-card>
    
      <table mat-table [dataSource]="courses" class="mat-elevation-z8">
      
      <ng-container matColumnDef="courseOrderID">
        <th mat-header-cell *matHeaderCellDef>Course Order ID</th>
        <td mat-cell *matCellDef="let element"> {{element.courseOrderID}}</td>
      </ng-container>
      
       <ng-container matColumnDef="title">
          <th mat-header-cell *matHeaderCellDef>Course Title </th>
          <td mat-cell *matCellDef="let element"> {{element.title}}</td>
      </ng-container>
      <ng-container matColumnDef="description">
          <th mat-header-cell *matHeaderCellDef>Course Description </th>
          <td mat-cell *matCellDef="let element"> {{element.description}}</td>
       </ng-container>
      <ng-container matColumnDef="duration">
          <th mat-header-cell *matHeaderCellDef>Duration </th>
          <td mat-cell *matCellDef="let element"> {{element.duration}}</td>
      </ng-container>
      <ng-container matColumnDef="scheduledDate">
        <th mat-header-cell *matHeaderCellDef>Scheduled Date </th>
      <td mat-cell *matCellDef="let element">
         <mat-form-field>
              <input matInput [matDatepicker]="picker" placeholder="Choose a date">
              <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
              <mat-datepicker #picker></mat-datepicker>
          </mat-form-field>
         {{element.scheduledDate}}</td>
      </ng-container>
      <ng-container matColumnDef="trainer">
          <th mat-header-cell *matHeaderCellDef>Trainer </th>
          <td mat-cell *matCellDef="let element">
              <mat-form-field><input matInput color="warn" *ngIf="!element.trainer"></mat-form-field> {{element.trainer}}</td>
      </ng-container>
      <ng-container matColumnDef="save">
          <th mat-header-cell *matHeaderCellDef></th>
          <td mat-cell *matCellDef="let element">
              <button mat-raised-button color ="primary" type ="submit" (click)="onSaveAssignment(trainee, element, picker)">Save</button></td>
      </ng-container>
      <tr mat-header-row *matHeaderRowDef="coursesdisplayColumns">
      </tr>
      <tr mat-row *matRowDef="let courses; columns: coursesdisplayColumns"></tr>
      </table>
      <br>
 
      </mat-card>

And this is my TypeScript code:

这是我的 TypeScript 代码:

import { Trainee } from '../trainees.model';
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs';
import { TraineesService } from '../../trainees.service';
import { ActivatedRoute, ParamMap } from '@angular/router';
import { Course } from '../../courses/courses.model';
import { CoursesService } from '../../courses.service';
import { Assignment } from '../../assignments/assignments.model';
import { NgForm } from '@angular/forms';

@Component({
  selector: 'app-trainee-details',
  templateUrl: './trainee-details.component.html',
  styleUrls: ['./trainee-details.component.css']
})


export class TraineeDetailsComponent implements OnInit, OnDestroy {
  
  private traineeId: string;
  trainee: Trainee;
  assignment: Assignment;
  courses: Course[] = [];
  coursesdisplayColumns = ['courseOrderID', 'title','description','duration','scheduledDate','trainer','save'];
  
  constructor(public traineeService: TraineesService, public route: ActivatedRoute, public coursesService: CoursesService){}

  ngOnInit() {
    this.route.paramMap.subscribe((paramMap: ParamMap) => {
      if(paramMap.has('traineeId')){
        this.traineeId = paramMap.get('traineeId');
        this.trainee = this.traineeService.getTrainee(this.traineeId);
      }
    });
    this.coursesService.getCoursesByJob(this.trainee.job);
    this.coursesService.getCoursesUpdateListener().subscribe((courses: Course[]) =>{
      this.courses = courses;
    });
  }

  onDelete(traineeId: string)
  {
    this.traineeService.deleteTrainee(traineeId);
  }
  onSaveAssignment(trainee: Trainee, selectedCourse: Course, dateForm: Date){
  
    console.log(trainee.id);
    console.log(selectedCourse.description);
    console.log(dateForm);
  }
  ngOnDestroy() {

  }
}

When i call onSaveAssignment(), the trainee ID and course ID are getting logged in the console correctly as those are defined in typescript, but I have no ideea how should i bring that date selected in the interface, i tried with ng-model but it did not work and I had to define a form for each input and still did not work.

当我调用 onSaveAssignment() 时,学员 ID 和课程 ID 正确登录到控制台,因为它们在打字稿中定义,但我不知道我应该如何在界面中选择该日期,我尝试使用 ng-model 但它不起作用,我不得不为每个输入定义一个表单,但仍然不起作用。

Is there any way to get that values from inputs on each row when the Save button is pressed ?

当按下“保存”按钮时,有没有办法从每一行的输入中获取这些值?

Or if i put 1 button for all of them is there any way to do a foreach on every input value in the interface ?

或者,如果我为所有这些按钮放置 1 个按钮,有没有办法对界面中的每个输入值执行 foreach 操作?

回答by Powkachu

You can get the values with ngModel by creating an object containing all values using the index as attribute.

您可以通过使用索引作为属性创建包含所有值的对象来使用 ngModel 获取值。

In you component, put an object:

在你的组件中,放置一个对象:

public myDates : any = {};

Then use ngModel with the index for your input date:

然后将 ngModel 与输入日期的索引一起使用:

<ng-container matColumnDef="scheduledDate">
  <th mat-header-cell *matHeaderCellDef>Scheduled Date </th>
  <td mat-cell *matCellDef="let element; let i = index">
    <mat-form-field>
      <input matInput [(ngModel)]="myDates[i]" [matDatepicker]="picker" placeholder="Choose a date">
      <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
      <mat-datepicker #picker></mat-datepicker>
    </mat-form-field>
  </td>
</ng-container>

For each row, it will add an attribute to the object myDates. Using index permits to guarantee uniqueness. Your object will look like: {1: date1, 2: date2 ...}.

对于每一行,它将向对象添加一个属性myDates。使用索引允许保证唯一性。你的对象将是这样的:{1: date1, 2: date2 ...}

Then you can get the value by knowing the index of the row. You can get it directly when clicking on the button:

然后你可以通过知道行的索引来获取值。点击按钮可以直接获取:

<ng-container matColumnDef="save">
  <th mat-header-cell *matHeaderCellDef></th>
  <td mat-cell *matCellDef="let element; let i = index">
    <button mat-raised-button color ="primary" type ="submit" (click)="onSaveAssignment(trainee, element, myDates[i])">Save</button>
  </td>
</ng-container>