Reputation: 159
I'm trying to create a custom component in angular + ngx-materialize that encapsulates logic of tags for a person using chips component. So I need to provide double binding between Person component and my tags component.
I've created the component and I'm able to listen to changes from the tags component so the person gets the new values. Nevertheless, when the value changes in the person, the tags do not update.
<app-input-conocimientos [(conocimientosSeleccionados)]="conocimientosSeleccionados"></app-input-conocimientos>
<button (click)="actualizarConocimientos()">Actualizar</button>
<button (click)="verConocimientos()">Ver</button>
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-prueba',
templateUrl: './prueba.component.html',
styleUrls: ['./prueba.component.css']
})
export class PruebaComponent implements OnInit {
constructor() { }
private conocimientosSeleccionados: any[] = [];
ngOnInit() {
}
actualizarConocimientos() {
this.conocimientosSeleccionados.push({ tag: "Hello world" });
}
verConocimientos() {
console.log(this.conocimientosSeleccionados);
}
}
<mz-chip-input [placeholder]="'Conocimientos...'" [secondaryPlaceholder]="'+Conocimiento'" [(ngModel)]="chips"
[autocompleteOptions]="posiblesConocimientos" [(ngModel)]="conocimientosSeleccionados" (add)="onAdd($event)"
(delete)="onDelete($event)">
</mz-chip-input>
import { Component, OnInit, Input, ChangeDetectorRef, Output, EventEmitter } from '@angular/core';
import { ConocimientosService } from '../conocimientos.service';
@Component({
selector: 'app-input-conocimientos',
templateUrl: './input-conocimientos.component.html',
styleUrls: ['./input-conocimientos.component.css']
})
export class InputConocimientosComponent implements OnInit {
@Input() conocimientosSeleccionados: Materialize.ChipDataObject[];
@Output() conocimientosSeleccionadosChange = new EventEmitter();
posiblesConocimientos: Materialize.AutoCompleteOptions;
constructor(private cdr: ChangeDetectorRef) { }
onAdd() {
this.avisarDeCambios();
}
onDelete() {
this.avisarDeCambios();
}
avisarDeCambios() {
this.conocimientosSeleccionadosChange.emit(this.conocimientosSeleccionados);
}
}
What should happen is, when the button "Actualizar" is pressed, the chip "Hello world" should be added and visible in the chips component.
Upvotes: 0
Views: 275
Reputation: 3699
I don't know whether it's an issue in current case, but you specified [(ngModel)]
twice on <mz-chip-input>
component:
[(ngModel)]="chips"
and...
[(ngModel)]="conocimientosSeleccionados"
Try to remove the first one.
Update
I've checked ngx-materialize
library, and it's said that you need to recreate an array every time you change it (because they use OnPush
change detection strategy).
Try to change this line
this.conocimientosSeleccionados.push({ tag: "Hello world" });
with this:
this.conocimientosSeleccionados = [...this.conocimientosSeleccionados, { tag: "Hello world" }];
Upvotes: 1