![](/img/trans.png)
[英]What is the proper way to initialize a property with @Input decorator in Angular2?
[英]Angular2 decorator for 2 way property binding
來自 Victor Savkin 關於Angular2 模板語法的帖子,展示了如何使用輸入和輸出屬性綁定 -
<todo-cmp [model]="todo" (complete)="onCompletingTodo(todo)"></todo-cmp>
@Component({selector: 'todo-cmp'})
class TodoCmp {
@Input() model;
@Output() complete = new EventEmitter(); // TypeScript supports initializing fields
}
輸入屬性用@Input() 修飾,而輸出屬性用@Output() 修飾。 我應該如何聲明將具有 2 種屬性綁定的屬性? 示例:假設 rootpanel 組件具有“suggestions”屬性(字符串類型)並且 searchPanel 具有“getSuggestions”屬性。 現在我希望這兩個屬性以兩種方式相互綁定。 我試過 -
根面板.html:
<search-panel [(getSuggestions)]="suggestions"> </search-panel>
但是我在 searchPanel 組件中聲明 getSuggestions 屬性時卡住了。 另外 getSuggestions 屬性的類型應該是什么 - string or EventEmitter<string>
?
請建議。
如果你想從父組件進行雙向模型綁定:
[(model)]
您的子組件中需要以下內容:
@Input() model: string;
@Output() modelChange:EventEmitter<string>;
在某些時候,當模型在您的子組件中被覆蓋時,您將發出modelChange
事件:
updateModel(newValue:string) {
this.model = newValue;
this.modelChange.emit(this.model);
}
從父組件的角度來看, [(model)]
等同於:
[model]="model" (modelChange)="model=$event"
這樣,當子組件內部的模型屬性發生變化時,模型的變化會通過雙向綁定向上傳播,沿途同步所有綁定的模型。
如果您想使用[(getSuggestions)]
樣式進行雙向綁定,請聲明如下字段
class TodoCmp {
@Input() getSuggestions;
@Output() getSuggestionsChange = new EventEmitter();
onClick() {
getSuggestions = 'someValue';
getSuggestionsChange.emit(getSuggestions);
}
}
對於這樣的輸入/輸出組合, getSuggestions
可能不是一個好的選擇,但它應該展示它們是如何連接的。 輸出需要與輸入具有相同的名稱,並帶有額外的Change
。 如果此命名方案不適合使用您的組件,例如
<search-panel [suggestions]="suggestions" (getSuggestions)="updateSuggestions($event)> </search-panel>
輸入/輸出像
class TodoCmp {
@Input() suggestions;
@Output() getSuggestions = new EventEmitter();
onClick() {
suggestions = 'someValue';
getSuggestions.emit(getSuggestions);
}
}
pixelbits 推薦的方法正是你應該如何做到這一點,但如果你在一個組件上有多個雙向數據綁定屬性,或者甚至在你的代碼庫中經常更改的屬性,我為此創建了一個裝飾器。 如果你在這里使用 npm,它就是。 如果您需要代碼,請轉到 gihub 頁面。
有了這個,你可以直接使用:
import { Component } from '@angular/core'; import { TwoWay } from 'two-way-decorator'; @Component({ selector: 'app-example', templateUrl: './example.component.html', styleUrls: ['./example.component.scss'] }) export class ExampleComponent { @TwoWay() public text: string; @TwoWay() public count: number; }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.