core.js:10101 NG0303: Не может привязаться к ‘matCellDefOf’, так как это неизвестное свойство ‘td’

#angular

Вопрос:

я пытаюсь использовать таблицу мата из углового материала, поэтому консоль показывает ошибку, как вы видите на этом рисунке

core.js:10101 NG0303: Не может быть привязан к «matCellDefOf», поскольку это неизвестное свойство «td». введите описание изображения здесь

и вот код

   <div class="row">
        <div class="col-xl-12">

            <div [hidden]="objectifs.length">
                    <div class="alert alert-warning" role="alert">
                            <i class="fas fa-exclamation-triangle">   Vous n'avez pas des objectifs à evaluer !</i>
                          </div>
                          
                     </div>  

<div [hidden] ="!objectifs.length">

<mat-form-field>
        <mat-label>Recherche</mat-label>
        <input matInput (keyup)="applyFilter($event)" placeholder="..." #input>
      </mat-form-field>
      
      <div class="mat-elevation-z8">
        <table mat-table [dataSource]="dataSource" matSort>
      
          <!-- Num Column -->
          <ng-container matColumnDef="position">
              <th mat-header-cell *matHeaderCellDef mat-sort-header> Num. </th>
              <td mat-cell *matCellDef="let i = index">
              {{this.paginator.pageIndex == 0 ? i   1 : 1   i   this.paginator.pageIndex * this.paginator.pageSize}}
              </td>
            </ng-container>
      
          <!-- designation Column -->
          <ng-container matColumnDef="designation">
            <th mat-header-cell *matHeaderCellDef mat-sort-header> Designation </th>
            <td mat-cell *matCellDef="let row"> {{row.designation}} </td>
          </ng-container>


          <!-- autoEvaluation Column -->
          <ng-container matColumnDef="autoEvaluation">
            <th mat-header-cell *matHeaderCellDef mat-sort-header> Evaluation </th>
            <td mat-cell *matCellDef="let objectif of objectifs">
                    <mat-form-field appearance="fill" style="width:60%">
                            <mat-label>Evaluer</mat-label>
                                <mat-select (selectionChange)="change(objectif)" name={{objectif.autoEvaluation}}{{objectif.designation}} [(ngModel)]="objectif.autoEvaluation" id="select">
                                    <mat-option [hidden]="!objectif.autoEvaluation" [value]="objectif.autoEvaluation" selected>
                                        {{ objectif.autoEvaluation }}
                                        </mat-option>
                                    <mat-option *ngFor="let eval of evaluations" [value]="eval.designation" ng-reflect-value = "eval.designation">
                                    {{ eval.designation }}
                                    </mat-option>
                                  </mat-select>
                          </mat-form-field>
                         </td>
          </ng-container>
      
                <!-- commentaire Column -->
                
                <ng-container matColumnDef="commentaire" >
                        <th mat-header-cell *matHeaderCellDef mat-sort-header> Commentaire </th>
                        <td mat-cell *matCellDef="let objectif of objectifs">
                        <textarea  (change)="change(objectif)" class="form-control" placeholder="commentaire" value={{objectif.commentaire}} [(ngModel)]="objectif.commentaire" rows="1" id="comm">
                            </textarea>
                        </td>
                      </ng-container>
                    
      
          <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
          <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
      
          <!-- Row shown when there is no matching data. -->
          <tr class="mat-row" *matNoDataRow>
            <td class="mat-cell" colspan="4">Aucun résultat pour "{{input.value}}"</td>
          </tr>
        </table>
      
        <mat-paginator [pageSizeOptions]="[5, 10, 25, 100]"></mat-paginator>
      </div>
      
      <div class="alert alert-success alert-dismissible fade show col-6 mt-3" role="alert" *ngIf ="submitted">
            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
              <span aria-hidden="true">amp;times;</span>
            </button>
            <span id="success"> <strong><i class="fas fa-exclamation-circle">  Votre auto-évaluation a été sauvgarder avec success !</i></strong></span>
          </div>
        <button type="button" (click)="autoEvaluate()" class="btn btn-success mx-auto d-block mt-2" id="submit"><i class="feather icon-check-circle"></i>Valider</button>
        </div>
        </div>
</div>
 

введите описание изображения здесь

 import { Component, OnInit, ViewChild, AfterViewInit } from '@angular/core';
import { Objectif } from 'src/models/objectif';
import { ObjectifService } from 'src/Services/objectif.service';
import { MatTableDataSource } from '@angular/material/table';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { FormGroup, FormControl } from '@angular/forms';
import {MatTableModule} from '@angular/material/table';

@Component({
    selector: 'app-auto-evaluation',
    templateUrl: './auto-evaluation.component.html',
    styleUrls: ['./auto-evaluation.component.scss']
})
export class AutoEvaluationComponent implements AfterViewInit {

    objectifs: Array<Objectif> = [];
    tempList: Array<Objectif> = [];
    submitted = false;
    err = false;
    evaluations = [
        { "id": 1, "designation": "Performance a ameliore" },
        { "id": 2, "designation": "Zone de conformite" },
        { "id": 3, "designation": "Objectif dépassé" },
        { "id": 4, "designation": "Performance exceptionnelle" }
    ];
    //Mat table
    displayedColumns: string[] = ['position', 'designation', 'autoEvaluation', 'commentaire'];
    dataSource: MatTableDataSource<Objectif>;


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

    constructor(private objectifService: ObjectifService) {

        this.getAllObjectifs();
    }
    ngAfterViewInit() {

    }
    getAllObjectifs() {

        this.objectifService.getObjectifsList().subscribe(data => {
            this.objectifs = data,
                this.dataSource = new MatTableDataSource(this.objectifs);
            this.dataSource.paginator = this.paginator;
            this.dataSource.sort = this.sort;
        });
    }
    autoEvaluate() {

        for (let i = 0; i < this.tempList.length; i  ) {
            this.objectifService.saveObjectif(this.tempList[i]).subscribe();
        }
        this.submitted = true;
    }

    change(objectif: Objectif) {
        let flag = false;
        if (this.tempList.length == 0) {
            this.tempList.push(objectif);
        }
        else {
            for (let i = 0; i < this.tempList.length; i  ) {
                if (this.tempList[i] == objectif) {
                    console.log("objectif found ! saving changes on a temp list  list ");
                    flag = true;
                    this.tempList[i].autoEvaluation = objectif.autoEvaluation;
                    this.tempList[i].commentaire = objectif.commentaire;
                }
                if (flag == false) {
                    console.log("objectif not found time to push a new objectif ");
                    this.tempList.push(objectif);
                }
            }
        }
    }
    applyFilter(event: Event) {
        const filterValue = (event.target as HTMLInputElement).value;
        this.dataSource.filter = filterValue.trim().toLowerCase();

        if (this.dataSource.paginator) {
            this.dataSource.paginator.firstPage();
        }
    }


    form = new FormGroup({
        supName: new FormControl()
    });




}
 

мой пакет.json

 {
  "name": "sofrecom-dashboard-evaluation",
  "version": "1.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e",
    "postinstall": "ngcc"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^12.0.1",
    "@angular/cdk": "^12.0.1",
    "@angular/common": "^12.0.1",
    "@angular/compiler": "^12.0.1",
    "@angular/core": "^12.0.1",
    "@angular/forms": "^12.0.1",
    "@angular/localize": "^12.0.1",
    "@angular/material": "^12.0.1",
    "@angular/platform-browser": "^12.0.1",
    "@angular/platform-browser-dynamic": "^12.0.1",
    "@angular/router": "^12.0.1",
    "@ks89/angular-modal-gallery": "^7.2.7",
    "@ng-bootstrap/ng-bootstrap": "^4.0.1",
    "angular-morris-js": "^0.3.0",
    "bootstrap": "^4.6.0",
    "d3": "^3.5.17",
    "jquery": "^3.6.0",
    "moment": "^2.29.1",
    "morris.js": "^0.5.0",
    "mousetrap": "^1.6.2",
    "ng-click-outside": "^4.0.0",
    "ngx-perfect-scrollbar": "^6.3.1",
    "raphael": "^2.3.0",
    "rxjs": "^6.5.5",
    "rxjs-compat": "^6.6.7",
    "screenfull": "^4.2.0",
    "tslib": "^2.0.0",
    "zone.js": "~0.11.4"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "^12.0.1",
    "@angular/cli": "^12.0.1",
    "@angular/compiler-cli": "^12.0.1",
    "@angular/language-service": "^12.0.1",
    "@types/hammerjs": "^2.0.39",
    "@types/jasmine": "~3.6.0",
    "@types/jasminewd2": "~2.0.3",
    "@types/jquery": "^3.5.5",
    "@types/mousetrap": "^1.6.6",
    "@types/node": "^12.20.8",
    "codelyzer": "^6.0.0",
    "jasmine-core": "~3.6.0",
    "jasmine-spec-reporter": "~5.0.0",
    "karma": "~6.3.2",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage-istanbul-reporter": "~3.0.2",
    "karma-jasmine": "~4.0.0",
    "karma-jasmine-html-reporter": "^1.5.0",
    "protractor": "~7.0.0",
    "ts-node": "~8.3.0",
    "tslint": "~6.1.0",
    "typescript": "^4.0.7"
  }
}
 

ps : все работает хорошо, но мне нужно исправить только эту ошибку .

Комментарии:

1. Пожалуйста, обновите свой вопрос и предоставьте более подробную информацию, включая примеры кода в вашем вопросе, а также пример минимального воспроизведения, если это возможно, чтобы сообщество могло помочь вам решить проблему.

2. кроме того, вы импортировали MatTableModule в свой модуль?

3. да , он импортирован , все работает, и результаты отображаются в моей таблице, на консоли отображается только ошибка, которую я хочу устранить .

4. Пожалуйста, добавьте код файла component.ts.

5. @AshotAleqsanyan пакет.json и html уже добавлены, вы можете проверить их .

Ответ №1:

Хорошо, я мог бы воспроизвести проблему в примере stackblitz. Проблема в том, что в вашем шаблоне есть несколько строк

  *matCellDef="let objectif of objectifs" 
 

matCellDef является структурной директивой и может определять свойства seleral на скриншоте, вы не можете определять свои собственные свойства с помощью собственного синтаксиса, это нарушит код.

после изменения этого *matCellDef="let objectif of objectifs" на *matCellDef="let objectif" него начните работать

введите описание изображения здесь

Комментарии:

1. @houcemabidi Я обновил ответ несколько секунд назад, пожалуйста, проверьте еще раз

2. большое вам спасибо , да, это работает, и хорошего вам дня 🙂