'How to use OnChanges in angular?
I need to load the varieties of each product, investigating they tell me that I can do it with an OnChanges that when selecting a product shows all the varieties of that product. here is the code of the ts and HTML, respectively.
this.listadoProductos = this.resolucionDatosCargados['listProduct'].map(item => ({
id: item[0],
name: item[1]
}));
this.parametros['producto'] = this.listadoProductos[0]['id'];
this.listadoVariedad = this.resolucionDatosCargados['listVariety'].map(item => ({
id: item[0],
idVar: item[1],
name: item[2]
}));
this.parametros['variedad'] = this.listadoVariedad[0]['id'];
<!-- Producto -->
<div fxLayout="row" fxLayoutGap="{{anchoEntreCombobox.MD}}">
<div fxFlex="80" class="bottom-margin">
<mat-form-field [style.width]="anchoCombobox.FULL">
<mat-select placeholder="Producto" [(ngModel)]="parametros.producto" name="product" [disabled]="parametros.todoProducto">
<mat-option *ngFor="let producto of listadoProductos" [value]="producto.id">{{ producto.name }}</mat-option>
</mat-select>
</mat-form-field>
</div>
<div fxFlex class="bottom-margin" fxLayoutAlign="start center">
<mat-checkbox [(ngModel)]="parametros.todoProducto" name="allProduct">Todos</mat-checkbox>
</div>
</div>
<!-- Variedad -->
<div fxLayout="row" fxLayoutGap="{{anchoEntreCombobox.MD}}">
<div fxFlex="80" class="bottom-margin">
<mat-form-field [style.width]="anchoCombobox.FULL">
<mat-select placeholder="Variedad" [(ngModel)]="parametros.variedad" name="variety" [disabled]="parametros.todaVariedad">
<mat-option *ngFor="let variedad of listadoVariedad" [value]="variedad.id">{{ variedad.name }}</mat-option>
</mat-select>
</mat-form-field>
</div>
<div fxFlex class="bottom-margin" fxLayoutAlign="start center">
<mat-checkbox [(ngModel)]="parametros.todaVariedad" name="allVariety">Todos</mat-checkbox>
</div>
</div>
Solution 1:[1]
If you want to implement onChanges in Angular. first of all you need to be passing data from one component to other as parent to child or child to parent. That is how you achieve.
selecting a product shows all the varieties of that product.
You need to implement SimpleChanges on your onChanges lifecycle hooks. and send or recieve data from components. This is just a demo as you dont have any child and parent intraction.
export class MainComponent implements OnInit,OnChanges {
constructor() { }
ngOnInit(){
}
ngOnChanges(change: SimpleChanges) {
if (change['nftId']) {
this.nftId = change['nftId'].currentValue;
}
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Hemanth Girimath |
