【问题标题】:How to make Ngx materialize chips double binding如何让 Ngx 实现芯片双绑定
【发布时间】:2019-06-14 10:46:05
【问题描述】:

我正在尝试在 angular + ngx-materialize 中创建一个自定义组件,该组件为使用芯片组件的人封装标签逻辑。所以我需要在 Person 组件和我的 tags 组件之间提供双重绑定。

我已经创建了组件,并且能够监听来自标签组件的更改,以便人们获得新值。然而,当人的值发生变化时,标签不会更新。

<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);
  }

}

应该发生的是,当按下“Actualizar”按钮时,应该添加芯片“Hello world”并在芯片组件中可见。

【问题讨论】:

    标签: angular angular-material ngx-chips


    【解决方案1】:

    我不知道这是否是当前情况下的问题,但您在 &lt;mz-chip-input&gt; 组件上指定了两次 [(ngModel)]

    [(ngModel)]="chips"
    and...
    [(ngModel)]="conocimientosSeleccionados"
    

    尝试删除第一个。

    更新

    我查过ngx-materialize库,据说每次更改都需要重新创建一个数组(因为他们使用OnPush更改检测策略)。

    尝试改变这一行

    this.conocimientosSeleccionados.push({ tag: "Hello world" });
    

    用这个:

    this.conocimientosSeleccionados = [...this.conocimientosSeleccionados, { tag: "Hello world" }];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-09
      • 1970-01-01
      • 1970-01-01
      • 2013-02-02
      相关资源
      最近更新 更多