Bidirectional data binding on the table

I am struggling to implement two-way data binding in a table between my .ts and my .html files. I have a structure that adds a new equipment to the array, and I want that new equipment to display on the table within the same screen.

I believe it involves using [(ngModel)], but I'm not sure.

Here is the code snippet:

export class EquipamentosCreateComponent implements OnInit {

  constructor() {
  }

  equipamentos: EquipamentoUnico[] = [
    {nameSaida: 'teste1', portaSaida: 'teste2'}
  ];


  displayedColumns: string[] = ['nameSaida', 'portaSaida'];

  equipamentoUnico: EquipamentoUnico = {
    nameSaida: '',
    portaSaida: ''
  }

  ngOnInit(): void {

  }

  addEquipamento(): void {
    this.equipamentos.push(this.equipamentoUnico);
    console.log(this.equipamentos);
    //console.log(equip);
  }

}
<mat-card>
    <mat-card-title>Cadastro Equipamento</mat-card-title>
    <form>
        <mat-form-field>
            <input matInput placeholder="Nome Saida" [(ngModel)]="equipamentoUnico.nameSaida" name="nameSaida">
        </mat-form-field>
        <mat-form-field>
            <input matInput placeholder="Porta Saida" [(ngModel)]="equipamentoUnico.portaSaida" name="portaSaida">
        </mat-form-field>
    </form>
    <button mat-raised-button (click)="addEquipamento()" color="primary">+</button>
</mat-card>

<div class="mat-elevation-z4">
    <table mat-table [dataSource]="equipamentos">

        <ng-container matColumnDef="nameSaida">
            <th mat-header-cell *matHeaderCellDef>nameSaida</th>
            <td mat-cell *matCellDef="let equipamentos;">{{equipamentos.nameSaida}}</td>
          </ng-container>

        <ng-container matColumnDef="portaSaida">
            <th mat-header-cell *matHeaderCellDef>portaSaida</th>
            <td mat-cell *matCellDef="let equipamentos">{{equipamentos.portaSaida}}</td>
        </ng-container>

        <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
      <tr mat-row *matRowDef="let equipamentos; columns: displayedColumns"></tr>
    </table>
</div>

Answer №1

The method AddEquipamento() you wrote is incorrect.

Here is the corrected code:

export interface UniqueEquipment {
  outputName: string;
  outputPort: string;
}

const EQUIPMENT_DATA: UniqueEquipment[] = [
  { outputName: 'test1', outputPort: 'test2' }
];

export class CreateEquipmentComponent implements OnInit {

  displayedColumns: string[] = ['outputName', 'outputPort'];

  uniqueEquipment: UniqueEquipment = {
    outputName: '',
    outputPort: ''
  }

  dataSource = new MatTableDataSource(EQUIPMENT_DATA);

  ngOnInit(): void {

  }

  addEquipment() {
    EQUIPMENT_DATA.push(this.uniqueEquipment);
    this.dataSource = new MatTableDataSource(EQUIPMENT_DATA);
    this.uniqueEquipment = {
      outputPort: '',
      outputName: ''
    };
  }

}}

Please correct these lines in your HTML:

<table mat-table [dataSource]="dataSource">
 <td mat-cell *matCellDef="let element;">{{element.outputName}}</td>
 <td mat-cell *matCellDef="let element;">{{element.outputPort}}</td>
 <tr mat-row *matRowDef="let row; columns: displayedColumns"></tr>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ignoring TypeScript overloads after the initial overload declaration

Issue An error occurs when attempting to call an overload method for a specific function. The call only works for the first defined overload, causing an error if the call is made to the second overload with mismatched typing compared to the first overload ...

Prevent automatic suggestions from appearing in Ionic app on Android

Our Ionic v4 (Angular, Cordova) app features form input fields (<ion-input>) like the example below: <ion-input formControlName="firstName" type="text" inputmode="text" autocapitalize="sentences"></ion-input> When running the Android ap ...

What methods can be utilized to gauge loading speed in Angular2?

Currently, I am working with Angular2 and I am looking to measure the loading time of my application. Within the app, there are 3 child components, two of which contain very heavy content that affects performance. In an attempt to improve this, I have ut ...

Oops! Looks like there was an issue with assigning to a reference or variable: Error: Uncaught (in promise)

I seem to be struggling with an issue that I believe may have been addressed before, but after reviewing other solutions, I am unable to pinpoint the error in my code. Any assistance in identifying my mistake would be greatly appreciated. <div class="j ...

The type 'NextApiRequest' lacks the following attributes compared to type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'

An error has been identified in the code for a Next.js project below. The error message reads: Argument of type 'NextApiRequest' is not assignable to parameter of type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any ...

How to add a service to a static function in Angular

After incorporating a logger service into my project, I have encountered an issue with using it in NGXS static selectors. The selectors in NGXS are static methods, which prevent me from accessing the logger service injected via Angular DI. Are there any e ...

Encountered an error while attempting to load http://localhost:9999/auth-service/oauth/token: The response for preflight request returned an unexpected HTTP status code

When attempting to generate an OAuth2 token, I utilized Spring Boot OAuth2 and Angular 5. In Postman and curl, I successfully generated the token by providing the appropriate values. However, when using the same parameters in the Angular POST request, it ...

Testing a feature in Angular that modifies a variable

Trying to test a function that updates a Boolean variable has been causing some confusion for me. The strange thing is, even though the function seems to be called successfully when using the toHaveBeenCalled method, the variable itself never actually gets ...

Using Cypress fixtures with TypeScript

After transitioning from using Cypress with Javascript specs to Typescript, I encountered a challenge in working with Fixtures. In Javascript, the approach below worked; however, I faced difficulties when switching to Typescript. Fixture JSON file: I sto ...

Having trouble locating a file in WebStorm? Try accessing WebStorm through the terminal instead

Starting WebStorm from the terminal Version: WebStorm 2016.3.3 I suspect that the reason it's not functioning is due to emojis in some of my file names. Do you think this could be the issue, or is there another root cause for the problem? Can emoji ...

Ways to access or modify variables from a different component in Angular 4 without relying on a service class

Is there a way to interact with or modify variables in another component without using a shared service? I'm dealing with two separate components in my Angular project. Keep in mind that these components are not related as Parent and Child. Compone ...

What is preventing Angular from letting me pass a parameter to a function in a provider's useFactory method?

app.module.ts bootstrap: [AppComponent], declarations: [AppComponent], imports: [ CoreModule, HelloFrameworkModule, ], providers: [{ provide: Logger, useFactory: loggerProviderFunc(1), }] ...

Finding a date from a calendar with a readonly property in Playwright

Just starting out with the playwright framework after working with Protractor before. I'm trying to figure out the correct method for selecting a date in Playwright. selector.selectDate(date) //having trouble with this ...

Having numerous occurrences of the identical root application in Angular 2

Our team has been successfully integrating Angular 2 into a legacy page, gradually enhancing its user-friendliness by replacing prerendered backend widgets with angular modules. However, we have encountered a challenge that I am unsure how to address: I h ...

Troubleshooting ngFor Issue in Angular 4

I've double-checked all the required modules and scanned for errors, but unfortunately, nothing seems to be helping me at the moment. As a newcomer to Angular, I'm still in the learning phase. Now, let's take a look at my app.module.ts file ...

Unable to install @angular/fire due to compatibility conflicts

Upon running npm outdated, I attempted to update some outdated packages without fully understanding the implications, thinking it was necessary for updating them. However, what I truly need is to install Angular Fire, as indicated by this error message: ...

*NgFor toggle visibility of specific item

Here is a snippet of HTML code that I'm working with: <!-- Toggle show hide --> <ng-container *ngFor="let plateValue of plateValues; let i=index"> <button (click)="toggle(plateValue)">{{i}}. {{ btnText }}</button> ...

Seeking assistance with producing results

Is there someone who can provide an answer? What will be the output of the code snippet below when logged to the console and why? (function(){ var a = b = 3; })(); console.log("Is 'a' defined? " + (typeof a !== 'u ...

Struggling to understand how to define and utilize Static variables in TypeScript? If you're finding that they are consistently coming up

export class myClass implements OnInit { counter = 0; static counter: any; onListItemClick(PackDef: PackDefinition): void { this.itemClicked.emit(PackDef); this.counter++; console.log(this.counter); } } and.. import { myClass } from '. ...

Issue with using NgControl in Angular when attempting to invoke writeValue

Dealing with a custom control and valueAccessor in the following code snippet: constructor( @Self() @Optional() public valueControl: NgControl ) { if( valueControl ) { valueControl.valueAccessor = this; } } writeValue( values: any ): void ...