Angular 5/6: ERROR Ошибка: поле mat-form должно содержать MatFormFieldControl

Я пытаюсь открыть окно OpenDialog из списка таблиц и получаю следующую ошибку: ОШИБКА Ошибка: поле mat-form должно содержать MatFormFieldControl.

вот код HTML openDialog:

<h2 mat-dialog-title>Edit Order</h2>

<mat-dialog-content >

    <mat-form-field>
        <mat-card-content *ngIf = "order.orderDate != null" [(ngModel)] = "order.orderDate" name = "orderDate" ngDefaultControl ></mat-card-content>
    </mat-form-field>
    <mat-form-field>
        <mat-card-content [(ngModel)] = "order.destAddress" name = "destAddress" ngDefaultControl></mat-card-content>
    </mat-form-field>
    <mat-form-field>
        <mat-card-content [(ngModel)] = "order.deliveryType" name = "deliveryType" ngDefaultControl></mat-card-content>
    </mat-form-field>
    <mat-form-field>
        <mat-card-content [(ngModel)] = "order.price" name = "price" ngDefaultControl ></mat-card-content>
    </mat-form-field>
    <mat-form-field>
        <mat-card-content [(ngModel)] = "order.status" name = "status" ngDefaultControl></mat-card-content>
    </mat-form-field>

</mat-dialog-content>

<mat-dialog-actions>
    <button class = "mat-raised-button"(click) = "close()">Close</button>
</mat-dialog-actions>

вот код компонента диалога

import { Component, OnInit, Inject } from '@angular/core';
import { MatDialogRef, MAT_DIALOG_DATA} from '@angular/material';
import { Order } from '../Order';
import { OrdersService} from '../orders.service';

export interface DialogData {
  orderId: number;
  customerId: number;
  motoboyId: number;
  orderDate: Date;
  localAddress: string;
  latitudeOriginAddress: number;
  longitudeOriginAddress: number;
  destAddress:string;
  latitudeDestAddress:number;
  longitudeDestAddress: number;
  price: number;
  collectDate: Date;
  deliveryDate: Date;
  contactDestination: string;
  phoneDestination:string;
  phoneNumber: string;
  deliveryType: string;
  status: string;
  active: boolean;
}

@Component({
  selector: 'app-order-screen',
  templateUrl: './order-screen.component.html',
  styleUrls: ['./order-screen.component.css']
})
export class OrderScreenComponent implements OnInit {

  showButton : boolean = true;
  order = new Order();
  constructor(private orderService: OrdersService, public dialogRef: MatDialogRef<OrderScreenComponent>, @Inject(MAT_DIALOG_DATA) public data: DialogData) {
    console.info(data);
    this.order = data;
  }

  ngOnInit() {
  }

  close() {
    this.dialogRef.close();
  }

}

вот код HTML, из которого должен быть открыт OpenDialog:

<div>
  <mat-form-field>
      <input matInput (keyup) = "applyFilter($event.target.value)" placeholder = "Filter">
    </mat-form-field>
    <button (click) = "refresh()">refresh</button>
<mat-table [dataSource] = "dataSource">
  <ng-container matColumnDef = "orderId">
    <mat-header-cell *matHeaderCellDef> Order Id </mat-header-cell>
    <mat-cell *matCellDef = "let order"> {{order.orderId}} </mat-cell>
  </ng-container>
  <ng-container matColumnDef = "customerId">
    <mat-header-cell *matHeaderCellDef> Customer </mat-header-cell>
    <mat-cell *matCellDef = "let order"> {{order.customer.firstName}} </mat-cell>
  </ng-container>
  <ng-container matColumnDef = "motoboyId">
    <mat-header-cell *matHeaderCellDef> Moto Boy </mat-header-cell>
    <mat-cell *matCellDef = "let order"> {{order.motoboy.firstName}} </mat-cell>
  </ng-container>
  <ng-container matColumnDef = "localAddress">
    <mat-header-cell *matHeaderCellDef> Local Address </mat-header-cell>
    <mat-cell *matCellDef = "let order"> {{order.localAddress}} </mat-cell>
  </ng-container>
  <ng-container matColumnDef = "destAddress">
    <mat-header-cell *matHeaderCellDef> Destenation Address </mat-header-cell>
    <mat-cell *matCellDef = "let order"> {{order.destAddress}} </mat-cell>
  </ng-container>
  <ng-container matColumnDef = "price">
    <mat-header-cell *matHeaderCellDef> Price </mat-header-cell>
    <mat-cell *matCellDef = "let order"> {{order.price}} </mat-cell>
  </ng-container>
  <ng-container matColumnDef = "orderDate">
    <mat-header-cell *matHeaderCellDef> Order Date </mat-header-cell>
    <mat-cell *matCellDef = "let order"> {{order.orderDate}} </mat-cell>
  </ng-container>
  <ng-container matColumnDef = "active">
    <mat-header-cell *matHeaderCellDef> isActive </mat-header-cell>
    <mat-cell  *matCellDef = "let order">
    <button *ngIf = "order.motoboy === null" (click) = "handleAsignToOrder(order)" >assign</button>

    </mat-cell>
  </ng-container>
  <ng-container matColumnDef = "actions">
    <mat-header-cell *matHeaderCellDef> Actions </mat-header-cell>>
    <mat-cell *matCellDef = "let order">  
      <button  matTooltip = "Edit Order" mat-raised-button (click) = "openDialog(order.orderId)" >Edit</button>
    </mat-cell>>
  </ng-container>
  <mat-header-row *matHeaderRowDef = "displayedColumns"></mat-header-row>
  <mat-row *matRowDef = "let row; columns: displayedColumns;"></mat-row>
</mat-table>
</div>

а вот код компонента принадлежит HTML.

import { Component, OnInit, Inject } from '@angular/core';
import { MatDialog, MatDialogRef, MatDialogConfig, MAT_DIALOG_DATA } from '@angular/material';
import { Order } from '../Order'
import { Observable } from 'rxjs';
import { OrdersService } from '../orders.service'
import { MatTableDataSource } from '@angular/material';
import { MotoBoy } from '../MotoBoy';
import { MotoService } from '../moto.service';
import { OrderScreenComponent } from '../order-screen/order-screen.component';


@Component({
  selector: 'app-table',
  templateUrl: './table.component.html',
  styleUrls: ['./table.component.css']
})
export class TableComponent implements OnInit {


  order: Order;
  currentMotoBoy: MotoBoy = new MotoBoy();
  orders: Array<Order> = new Array<Order>();
  dataSource =  new MatTableDataSource(this.orders);

  displayedColumns = ['orderId', 'customerId', 'motoboyId', 'localAddress', 'destAddress', 'price', 'orderDate', 'active', 'actions'];

  constructor(private ordersService: OrdersService, private motoService: MotoService, public dialog: MatDialog) {

  }

  ngOnInit() {
    // this.dataSource.data === this.order used this way to filter
    this.dataSource.data = this.ordersService.allOrders;
    this.ordersService.getAllOrders();
    this.ordersService.allOrdersObservable.subscribe((data) => {
      this.dataSource.data = data;
      console.info(this.dataSource.data)
    })
    this.motoService.singleMotoObservable.subscribe((data) => {
      this.currentMotoBoy = data;
      console.info(this.currentMotoBoy)
    })
  }




  openDialog(order_id) {
    let order = this.ordersService.findOrder(order_id)
    const dialogConfig = new MatDialogConfig();

    dialogConfig.disableClose = true;
    dialogConfig.autoFocus = true;

    dialogConfig.data = order
    console.info(order);
    this.dialog.open(OrderScreenComponent, dialogConfig);
  }


}

Я буду наслаждаться, чтобы вы мне помогли. Спасибо

Тестирование функциональных ngrx-эффектов в Angular 16 с помощью Jest
В системе управления состояниями ngrx, совместимой с Angular 16, появились функциональные эффекты. Это здорово и делает код определенно легче для...
Angular и React для вашего проекта веб-разработки?
Angular и React для вашего проекта веб-разработки?
Когда дело доходит до веб-разработки, выбор правильного front-end фреймворка имеет решающее значение. Angular и React - два самых популярных...
Эпизод 23/17: Twitter Space о будущем Angular, Tiny Conf
Эпизод 23/17: Twitter Space о будущем Angular, Tiny Conf
Мы провели Twitter Space, обсудив несколько проблем, связанных с последними дополнениями в Angular. Также прошла Angular Tiny Conf с 25 докладами.
Угловой продивер
Угловой продивер
Оригинал этой статьи на турецком языке. ChatGPT используется только для перевода на английский язык.
Мое недавнее углубление в Angular
Мое недавнее углубление в Angular
Недавно я провел некоторое время, изучая фреймворк Angular, и я хотел поделиться своим опытом со всеми вами. Как человек, который любит глубоко...
Освоение Observables и Subjects в Rxjs:
Освоение Observables и Subjects в Rxjs:
Давайте начнем с основ и постепенно перейдем к более продвинутым концепциям в RxJS в Angular
2
0
7 989
2

Ответы 2

Вы должны установить директиву matInput для html-элемента input внутри вашего элемента mat-form-field.

См. https://material.angular.io/components/form-field/overview для получения дополнительной информации.

Решение состоит в том, что вам нужно включить директиву matInput с mat-form-field или просто использовать простой тег

<h2 mat-dialog-title>Edit Order</h2>

<mat-dialog-content >

    <div>
        <mat-card-content *ngIf = "order.orderDate != null" [(ngModel)] = "order.orderDate" name = "orderDate" ngDefaultControl ></mat-card-content>

    <div>
        <mat-card-content [(ngModel)] = "order.destAddress" name = "destAddress" ngDefaultControl></mat-card-content>
    </div>
    <div>
        <mat-card-content [(ngModel)] = "order.deliveryType" name = "deliveryType" ngDefaultControl></mat-card-content>
    </div>
<div>
        <mat-card-content [(ngModel)] = "order.price" name = "price" ngDefaultControl ></mat-card-content>
    </div>
<div>
        <mat-card-content [(ngModel)] = "order.status" name = "status" ngDefaultControl></mat-card-content>
    </div>

</mat-dialog-content>

<mat-dialog-actions>
    <button class = "mat-raised-button"(click) = "close()">Close</button>
</mat-dialog-actions>

Что вы имели в виду, когда сказали использовать простой тег? не могли бы вы привести пример? благодарить

user2422556 01.07.2018 22:30

простой тег означает удаление <mat-form-field> </mat-form-field> вместо использования <div> </div>

Akj 02.07.2018 06:47

Другие вопросы по теме