簡體   English   中英

Angular2組件@Input雙向綁定

[英]Angular2 Component @Input two way binding

我有一個數據驅動的Angular應用程序。 我有一個切換組件,我以切換狀態傳遞。 我的問題是雙向數據綁定似乎不起作用,除非我將toggle布爾值作為對象傳遞。 有沒有辦法讓它在不使用EventEmitter或將變量作為對象傳遞的情況下工作。 這是一個可重用的組件,應用程序是大量數據驅動的,因此將值作為對象傳遞給非選項。 我的代碼是......

toggle.html

<input type="checkbox" [(ngModel)]="toggled" [id]="toggleId" name="check"/>

toggle.component.ts

import { Component, Input, EventEmitter, Output } from '@angular/core';

@Component({
  moduleId: module.id,
  selector: 'toggle-switch',
  templateUrl: 'toggle-switch.component.html',
  styleUrls: ['toggle-switch.component.css']
})

export class ToggleSwitchComponent {

  @Input() toggleId: string;
  @Input() toggled: boolean;

}

parent.component.html

<toggle-switch toggleId="toggle-1" [(toggled)]="nongenericObject.toggled"></toggle-switch>

對於[(toggled)]="..."你需要工作

  @Input() toggled: boolean;
  @Output() toggledChange: EventEmitter<boolean> = new EventEmitter<boolean>();

  changeValue() {
    this.toggled = !(this.toggled); 
    this.toggledChange.emit(this.toggled);
  }

另請參見雙向綁定

[更新] - 2019年6月25日
來自@Mitch的評論如下:
值得一提的是, @Output名稱必須相同@Input名稱,但Change的結束。 你無法在onToggle或其他東西上調用它。 這是一種語法約定。

雖然這個問題已超過2年,但我想貢獻5美分......

這不是關於Angular的問題,它關於Javascript如何工作......簡單的變量(數字,字符串,布爾值等)通過值傳遞,而復雜的(對象,數組)通過引用傳遞:

你可以在Kyle Simpson的系列中閱讀更多關於這個的內容你不知道js:

https://github.com/getify/You-Dont-Know-JS/blob/master/types%20%26%20grammar/ch2.md#value-vs-reference

因此,您可以使用@Input()對象變量來共享組件之間的范圍,而無需使用發射器,觀察器和類似的東西。

// In toggle component you define your Input as an config object
@Input() vm: Object = {};

// In the Component that uses toggle componet you pass an object where you define all needed needed variables as properties from that object:
config: Object = {
    model: 'whateverValue',
    id: 'whateverId'
};

<input type="checkbox" [vm]="config" name="check"/>

這樣,您可以修改所有對象屬性,並在兩個組件中獲得相同的值,因為它們共享相同的引用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM