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>