2016-09-25 38 views
1

當在<input>上通過[ngModel]使用單向綁定時,在輸入中輸入字符總是會將字符添加到<input>的值中。問題是,如果[ngModel]表達式繼續返回其現有值,則<input>值不會刷新。Angular 2 + ngrx/store:單向綁定到<input>

下面是一個簡單的例子:

@Component({ 
    selector: 'my-component', 
    template: ` 
    <input type="text" [ngModel]="foo.bar" /> 
    ` 
}) 
export class MyComponent { 
    private foo = { 
    bar: 'baz' 
    }; 
} 

我期望的輸入,總是顯示「巴茲」不管用戶輸入的,但這種情況並非如此。

我正在尋找這種行爲的原因是ngrx/store/redux應用程序,其中<input>的值應該由狀態單向流動來確定。我創建了一個example use case on Plunker,Misko Hevery的描述不應該是可編輯的。該模型確實沒有改變,但<input>顯示任何用戶類型。

在「No trackBy」部分,它正常工作,但僅僅是因爲Angular重畫了所有強制進行適當重新評估(但不是解決方案)的DOM元素。將disabledreadonly屬性添加到<input>對我來說不是一個可接受的答案,因爲組件應該不知道可能複雜的狀態邏輯,該邏輯不允許更改此字段。

我在React Redux中看到過這種行爲,我想知道如何在Angular 2中使用單向綁定,如果我們不能阻止用戶改變他們自己的視圖。

+0

你找到任何解決方案? – Marcel

回答

0
@Component({ 
    selector: 'my-component', 
    template: ` 
    <input type="text" [value]="foo.bar" /> 
//[ngModel] is for two way binding 
    ` 
}) 
export class MyComponent { 
    private foo = { 
    bar: 'baz' 
    }; 
} 
+0

將輸入字段的「[value]」屬性與您想要的任何內容綁定。更改輸入字段不會影響變量的實際值。讓我知道這是否有幫助。 – Rajiv

+0

您提到「[ngModel]用於雙向綁定」,但它與使用'[value]'具有完全相同的單向效果,這意味着更改輸入字段不會影響變量/模型的值屬性。在輸入值與模型不一致的情況下,它也有完全相同的問題,所以這根本不能幫助我。請嘗試[plunker](http://plnkr.co/edit/KIHLhXfnCOybN5EWFxMA?p=preview)並讓我知道你是否想出了別的東西。謝謝! – Skyler

0
down vote 
@Component({ 
    selector: 'my-component', 
    template: ` 
    <input type="text" [value]="foo.bar" (keydown) = "$event.preventDefault();"/> 
//add preventDefault() to keydown event to prevent user from changing the value shown in input field 
    ` 
}) 
export class MyComponent { 
    private foo = { 
    bar: 'baz' 
    }; 
} 
+1

這確實會阻止用戶的鍵進入輸入值,但不幸的是,它也會停止'(ngModelChange)'和'(change)'發射,所以我無法將新值傳播到reducer。 – Skyler

1

因爲ChangeDetection不會觸發時從狀態返回的值是一樣的,唯一的直接的方式做,這是通過結合customerDescriptionLocked財產商店的customer.descriptionLocked設置屬性在組件的構造函數中。我知道你不希望組件只讀,因爲你不希望組件知道狀態的邏輯來確定鎖。通過綁定到customerDescriptionLocked屬性,該組件仍不知道該設置的狀態邏輯。

<input type="text" placeholder="Description" [ngModel]="record.customerDescription" 
[readonly]="record.customerDescriptionLocked" (ngModelChange)="updateDescription(record, $event)" /> 

組件構造:

constructor(public store: Store<AppState>, private ref: ChangeDetectorRef){ 
    this.customerState = store.select('customer'); 
    this.customerState.subscribe((customerState:CustomerState) => { 
    this.dashboardRecords = customerState.customers.map((customer:Customer):DashboardRecord => { 
     return { 
     customerId: customer.id, 
     customerName: `${customer.personalInfo.firstName} ${customer.personalInfo.lastName}`, 
     customerDescription: customer.description, 
     customerDescriptionLocked: customer.descriptionLocked, 
     customerUpdateCount: customer.updated 
     }; 
    }) 
    }); 
}