I'm trying to make red the text inserted in a dynaymically created input (as many as the button is pressed) but I cannot get it right. I don't know how to access the value of the input in this case. I want to change the text depending on the condition that if the inserted number is bigger than other input in the form, its color becomes red.
This is the html
<form [formGroup]="formulario">
<label>
Capacidad
<input type="text" formControlName="capacidad" />
</label>
<label>
Max. Casas
<input type="text" formControlName="maxcasas" />
</label>
<div formArrayName="pesos">
<button (click)="addPeso()">Añadir peso</button>
<button (click)="deleteAllPesos()">Resetear</button>
<div *ngFor="let peso of pesos.controls; let i = index" [formGroupName]="i">
<label>
Peso:
<input [style.color]="<<<<value bigger than formulario.capacidad ? "red" ; "black">>>>> type="number" formControlName="peso" />
</label>
<label>
Nombre:
<input type="text" formControlName="nombre" type="text" />
</label>
<button (click)="deletePeso(i)">Borrar</button>
</div>
</div>
</form>
This is the relevant part of the ts
public formulario = this.fb.group({
capacidad: ["5"],
maxcasas: ["3"],
pesos: this.fb.array([
this.fb.group({
peso: this.fb.control(""),
nombre: this.fb.control("")
})
])
});
get pesos() {
return this.formulario.get("pesos") as FormArray;
}
The same way you are accesing programatically this. formulario.get("capacidad") // FormControl
<form [formGroup]="formulario">
<label>
Capacidad
<input type="text" formControlName="capacidad" />
</label>
<label>
Max. Casas
<input type="text" formControlName="maxcasas" />
</label>
<div formArrayName="pesos">
<button (click)="addPeso()">Añadir peso</button>
<button (click)="deleteAllPesos()">Resetear</button>
<div *ngFor="let peso of pesos.controls; let i = index" [formGroupName]="i">
<label>
Peso:
<input [style.color]="formulario.get('pesos').get(i).get('peso').value > formulario.get("capacidad").value ? "red" ; "black" type="number" formControlName="peso" />
</label>
<label>
Nombre:
<input type="text" formControlName="nombre" type="text" />
</label>
<button (click)="deletePeso(i)">Borrar</button>
</div>
</div>
</form>
```
Similarily to other answer, check the value of the specific form control in the loop, you can do it by the following:
[style.color]="pesos.at(i).get('peso').value > formulario.get('capacidad').value ? 'red' : 'black'"
EDIT: But you can also do pesos.controls[i].controls.peso.value
, but I like to use at
and get
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.