Как мы можем использовать встроенные раскрывающиеся списки одних и тех же значений несколько раз в таблице материалов?

Я создаю модуль расписания. Я хотел показать предметы в виде выпадающего списка за все 7 дней в таблице. (пожалуйста, обратитесь к изображению). введите описание изображения здесь Когда я выбираю тему в одном из этих раскрывающихся списков, значения заполняются во всех остальных раскрывающихся списках. Например, когда я выбираю английский язык в качестве темы в любом из раскрывающихся списков, все остальные раскрывающиеся списки в этой конкретной строке заполняются автоматически введите здесь описание изображения

Я пробовал давать разные имена для formControlName, но это не сработало.

Вот код:

<form [formGroup]="form">
<div class="example-container mat-elevation-z8">

    <mat-table #table [dataSource]="dataSource">

        <!-- Position Column -->
        <ng-container matColumnDef="day" sticky>
            <mat-header-cell *matHeaderCellDef> Days </mat-header-cell>
            <mat-cell *matCellDef="let element"> {{element.day}} </mat-cell>
        </ng-container>

        <!-- Name Column -->
        <ng-container matColumnDef="period1">
            <mat-header-cell *matHeaderCellDef> Period 1 </mat-header-cell>
            <mat-cell *matCellDef="let element">
                <mat-form-field floatLabel="never">
                    <mat-select [(ngModel)]="subjects1" formControlName = "subjects1" [(value)]="element.subjects" placeholder="Subjects">
                        <mat-option *ngFor="let subject of subjects" [value]="subject" >{{subject}}</mat-option>
                    </mat-select>
                </mat-form-field>
            </mat-cell>
        </ng-container>

        <!-- Weight Column -->
        <ng-container matColumnDef="period2">
            <mat-header-cell *matHeaderCellDef> Period 2 </mat-header-cell>
            <mat-cell *matCellDef="let element">
                <mat-form-field floatLabel="never">
                    <mat-select [(ngModel)]="subjects2" formControlName = "subjects2" [(value)]="element.subjects" placeholder="Subjects">
                        <mat-option *ngFor="let subject of subjects" [value]="subject" >{{subject}}</mat-option>
                    </mat-select>
                </mat-form-field>
            </mat-cell>
        </ng-container>

        <!-- Symbol Column -->
        <ng-container matColumnDef="period3">
            <mat-header-cell *matHeaderCellDef> Period 3 </mat-header-cell>
            <mat-cell *matCellDef="let element">
                <mat-form-field floatLabel="never">
                    <mat-select [(ngModel)]="subjectName" formControlName = "subjects3" [(value)]="element.subjects" placeholder="Subjects">
                        <mat-option *ngFor="let subject of subjects" [value]="subject" >{{subject}}</mat-option>
                    </mat-select>
                </mat-form-field>
            </mat-cell>
        </ng-container>

        <!-- Fav Column -->
        <ng-container matColumnDef="period4">
            <mat-header-cell *matHeaderCellDef> Period 4 </mat-header-cell>
            <mat-cell *matCellDef="let element">
                <mat-form-field floatLabel="never">
                    <mat-select [(ngModel)]="subjectName" formControlName = "subjects4" [(value)]="element.subjects" placeholder="Subjects">
                        <mat-option *ngFor="let subject of subjects" [value]="subject" >{{subject}}</mat-option>
                    </mat-select>
                </mat-form-field>
            </mat-cell>
        </ng-container>
        <ng-container matColumnDef="period5">
            <mat-header-cell *matHeaderCellDef> Period 5 </mat-header-cell>
            <mat-cell *matCellDef="let element">
                <mat-form-field floatLabel="never">
                    <mat-select [(ngModel)]="subjectName" formControlName = "subjects5" [(value)]="element.subjects" placeholder="Subjects">
                        <mat-option *ngFor="let subject of subjects" [value]="subject" >{{subject}}</mat-option>
                    </mat-select>
                </mat-form-field>
            </mat-cell>
        </ng-container>
        <ng-container matColumnDef="period6">
            <mat-header-cell *matHeaderCellDef> Period 6 </mat-header-cell>
            <mat-cell *matCellDef="let element">
                <mat-form-field floatLabel="never">
                    <mat-select [(ngModel)]="subjectName" formControlName = "subjects6" [(value)]="element.subjects" placeholder="Subjects">
                        <mat-option *ngFor="let subject of subjects" [value]="subject" >{{subject}}</mat-option>
                    </mat-select>
                </mat-form-field>
            </mat-cell>
        </ng-container>
        <ng-container matColumnDef="period7">
            <mat-header-cell *matHeaderCellDef> Period 7 </mat-header-cell>
            <mat-cell *matCellDef="let element">
                <mat-form-field floatLabel="never">
                    <mat-select [(ngModel)]="subjectName" formControlName = "subjects7" [(value)]="element.subjects" placeholder="Subjects">
                        <mat-option *ngFor="let subject of subjects" [value]="subject" >{{subject}}</mat-option>
                    </mat-select>
                </mat-form-field>
            </mat-cell>
        </ng-container>
        <ng-container matColumnDef="period8">
            <mat-header-cell *matHeaderCellDef> Period 8 </mat-header-cell>
            <mat-cell *matCellDef="let element">
                <mat-form-field floatLabel="never">
                    <mat-select [(ngModel)]="subjectName" formControlName = "subjects8" [(value)]="element.subjects" placeholder="Subjects">
                        <mat-option *ngFor="let subject of subjects" [value]="subject" >{{subject}}</mat-option>
                    </mat-select>
                </mat-form-field>
            </mat-cell>
        </ng-container>
        <ng-container matColumnDef="period9">
            <mat-header-cell *matHeaderCellDef> Period 9 </mat-header-cell>
            <mat-cell *matCellDef="let element">
                <mat-form-field floatLabel="never">
                    <mat-select [(ngModel)]="subjectName" formControlName = "subjects9" [(value)]="element.subjects" placeholder="Subjects">
                        <mat-option *ngFor="let subject of subjects" [value]="subject" >{{subject}}</mat-option>
                    </mat-select>
                </mat-form-field>
            </mat-cell>
        </ng-container>


        <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
        <mat-row *matRowDef="let row; columns: displayedColumns;"><input matInput placeholder="Enter start time" [ngxTimepicker]="editableDial" readonly formControlName="startTime">
            <ngx-material-timepicker #editableDial  [enableKeyboardInput]="true"></ngx-material-timepicker>
            <input matInput placeholder="Enter end time" [ngxTimepicker]="editableDiall" readonly formControlName="endTime">
            <ngx-material-timepicker #editableDiall  [enableKeyboardInput]="true"></ngx-material-timepicker></mat-row>
    </mat-table>
</div>

The following is my TS:

    'subjects' = ["English", "Maths", "Science", "Social", "Tamil"];
  form: FormGroup;
  displayedColumns = ['day', 'period1','period2','period3','period4', 'period5', 'period6', 'period7', 'period8', 'period9'];
  dataSource = new MatTableDataSource(ELEMENT_DATA);
  sectionName: string = null;
  public show: boolean = false;


  @ViewChild(MatPaginator) paginator: MatPaginator;
  @ViewChild(MatSort) sort: MatSort;

  constructor( private formBuilder: FormBuilder,
               public dialog: MatDialog) { }

  ngOnInit() {
    this.form = this.formBuilder.group({
      className: new FormControl(this.classes[0], Validators.required),
      sectionName: new FormControl(this.sections[0], Validators.required),
      subjects1: new FormControl(this.subjects[0], Validators.required),
      subject2: new FormControl(this.subjects[0], Validators.required),
      subject3: new FormControl(this.subjects[0], Validators.required),
      subject4: new FormControl(this.subjects[0], Validators.required),
      subject5: new FormControl(this.subjects[0], Validators.required),
      subject6: new FormControl(this.subjects[0], Validators.required),
      subject7: new FormControl(this.subjects[0], Validators.required),
      subject8: new FormControl(this.subjects[0], Validators.required),
      subject9: new FormControl(this.subjects[0], Validators.required),
      startTime: ['', ValidationService.requiredField],
      endTime: ['', ValidationService.requiredField],
    });
  }

  addNew() {
    this.addOrEdit();
  }
   onSubmit(){
    console.log(this.form);
   }

  addOrEdit(id: any = -1) {
    let dialogRef = this.dialog.open(AddTimetableComponent,{
      width: '1200px',
      data: {
        titleLabel: (id == -1) ? 'Add' : 'Edit',
        isEditAction: (id == -1) ? false : true,
        //editData: (id == -1) ? '' : this.timeTable[id]
      },
      disableClose: true,
      //width: '50vw',
      //panelClass: this.commonUtilService.getPanelClass('full-screen-dialog'),
    });


  }

  toggle(){
    this.show = !this.show;
  }
}
export interface Element {

    day: string;
    weight: number;
    symbol: string;
    period1: string;
    period2: string;
    period3: string;
    period4: string;
    period5: string;
    period6: string;
    period7: string;
    period8: string;
    period9: string;
}
// @ts-ignore
// @ts-ignore
const ELEMENT_DATA: Element[] = [
    { day: 'Monday',period1: "",period2: "",period3: "",period4: "",period5: "",period6: "",period7: "",period8: "",period9: ""},
    { day: 'Tuesday', period1: "",period2: "",period3: "",period4: "",period5: "",period6: "",period7: "",period8: "",period9: ""},
    { day: 'Wednesday',period1: "",period2: "",period3: "",period4: "" ,period5: "",period6: "",period7: "",period8: "",period9: ""},
    { day: 'Thursday',  period1: "",period2: "",period3: "",period4: "",period5: "",period6: "",period7: "",period8: "",period9: "" },
    { day: 'Friday',  period1: "",period2: "",period3: "",period4: "",period5: "",period6: "",period7: "",period8: "",period9: "" },
    { day: 'Saturday',  period1: "",period2: "",period3: "",period4: "",period5: "",period6: "",period7: "",period8: "",period9: "" },
    { day: 'Sunday', period1: "",period2: "",period3: "",period4: "",period5: "",period6: "",period7: "",period8: "",period9: "" },

];

Есть ли другой способ реализовать эту идею? Или я делаю что-то не так, используя несколько раскрывающихся списков с похожими значениями в качестве встроенного?

Ожидаемый результат: я не хочу, чтобы все раскрывающиеся списки заполнялись при нажатии только одного из них.

Любая помощь, связанная с этим, будет высоко оценена.

Заранее спасибо!!


person krishie    schedule 29.07.2019    source источник


Ответы (1)


Необходимо изменить имя субъекта в ngModel с разными переменными для каждого файла . В противном случае Angular автоматически обновит все файлы .

person ajeesh s    schedule 29.07.2019
comment
Это не дало мне результата, но я нашел решение. Мне придется изменить имена [(value)]=element.subjects для заданных раскрывающихся списков, и это сработало отлично. Спасибо, что напомнили мне, что у всех записей не должно быть одинаковых имен. - person krishie; 29.07.2019