我有一個帶有 PrimeNG 的 Angular 應用程式。我正在使用這樣的 PickList 組件:
<p-pickList
[source]="source"
[target]="target"
>
<ng-template
let-item
pTemplate="item">
{{item | json}}
</ng-template>
</p-pickList>
<h2>source</h2>
<ul>
<li *ngFor="let s of source">{{s|json}}</li>
</ul>
<h2>target</h2>
<ul>
<li *ngFor="let t of target">{{t|json}}</li>
</ul>
組件本身很簡單:
@Component({
selector: 'app-hello',
templateUrl: './hello.component.html',
styleUrls: ['./hello.component.css'],
})
export class HelloComponent {
source: string[];
target: string[] = [];
constructor() {
this.source = [
"foo",
"bar",
"baz",
];
}
}
我這里沒有使用雙向系結,那么 PrimeNG 是如何更新源和目標屬性的呢?
在我的主要專案源和目標上是 @Input() 屬性,因此我不希望某些子組件擺弄它。PrimeNG 怎么可能改變這些價值觀?
uj5u.com熱心網友回復:
您可以復制 和 的值source,target然后HelloComponent將這些副本用于底層 PrimeNG PickList 小部件。這允許您將更新傳遞給HelloComponent將向下傳達給 PrimeNG 小部件,但對 PrimeNG 小部件中的這些陣列的更改不會影響原始輸入陣列。
我相信在您的原始代碼中,作為輸入傳遞給 的原始陣列HelloComponent,然后傳遞給 PrimeNG 小部件,是由“參考的副本”傳遞的。
private _sourceOptions: string[];
@Input set sourceOptions(options: string[]) {
// Ensure we're not passing a reference to the array down because it may still
// be changed. Create a new array with the same items. This can also help with
// firing change detection in the PrimeNG widget.
this._sourceOptions = options.slice(0);
}
get sourceOptions(): string[] {
return this._sourceOptions;
}
<!-- Component template file -->
<p-pickList [source]="sourceOptions" [target]="target">
<ng-template let-item pTemplate="item">
{{item | json}}
</ng-template>
</p-pickList>
uj5u.com熱心網友回復:
奇怪的是,在 primeNG 的組件中有一個 OnChange 偵聽器,一般來說,當一個 @Input 中的某些內容發生變化時,它確實會觸發一個 onChange 事件。
正如 Angular 檔案所說(https://angular.io/api/core/OnChanges),只要資料系結屬性發生更改,它就會觸發 onChange。在這種情況下,目標是一個資料系結屬性。
另外,改變價值觀是什么意思?如果選擇foo它會變成foobar? 在幕后,primeNG 并沒有處理您傳遞給它的資料,它可能有自己的內部存盤,用于顯示其選擇器串列組件的資料。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/420570.html
標籤:
