I have a formArray in my mat-table where three rows are displayed. Now I want to have a different text for placeholder in each row in the column name, for example test1, test2, test3. What is the best way to implement this?
My Code:
<div formArrayName="rows" *ngIf="attributesWithFormControls.includes(column.attribute); else otherColumns">
<span id="edit-cell" [formGroupName]="i">
<mat-form-field id="edit-calc-input">
<label>
<input matInput type="text" [formControlName]="column.attribute">
</label>
</mat-form-field>
</span>
</div>
// To use input fields in template
public attributesWithFormControls = [
"productNumber",
"name",
"weight",
"amount"
];
ngOnInit() {
this.columns = this.displayedColumns.map(c => c.attribute);
if (this.dataSource === null) {
this.dataSource = new MatTableDataSource([]);
}
// myForm
this.myForm = this.formBuilder.group({
rows: this.formBuilder.array([this.initItemRows()])
});
}
// Convenience getter for easy access to form fields
get f() {
return this.myForm.controls;
}
get formArr() {
return this.myForm.get("rows") as FormArray;
}
initItemRows() {
return this.formBuilder.group({
productNumber: [""],
name: [""],
weight: [""],
amount: [""]
});
}
Here is my work in StackBlitz
REVISION USING FORM CONTROL
If you wanted to do this from your
formGroup
, you could accomplish this with the following.Create a helper function to return the placeholder text base on
index
In your
addRow
function get the placeholder text and set it to the propertyplaceholder
in yournewItem.value
objectIn your HTML markup access that property value from the
row
STACKBLITZ
https://stackblitz.com/edit/angular-l9x7ac-oxq4qq?file=app/table-basic-example.html
REVISION NON FORM CONTROL
Create a helper function to return the placeholder text base on
index
In HTML markup via the
placeholder
attribute call the helper function and passi
as the argument.STACKBLITZ
https://stackblitz.com/edit/angular-l9x7ac-6aq6u6?file=app%2Ftable-basic-example.html
ORIGINAL ANSWER
Modify your interface to include
placeholder
property.Add property with placeholder value to your column attributes array.
In HTML markup, use the
placeholder
attribute on thematInput
and pass in your value via[placeholder]="column.placeholder"
STACKBLITZ
https://stackblitz.com/edit/angular-l9x7ac-psmqzu?file=app/table-basic-example.html