angular - 将数据从组件传递到对话框,但不是 2 路模型绑定
问题描述
目前,我有水果组件和更新水果组件。水果组件负责显示不同的水果片和更新这些片的按钮。当前选择的水果在对话数据中传递
水果组件 Html
<div>
<mat-chip-list *ngFor="let fruit of selectedFruits">
<mat-chip>{{ fruit }}</mat-chip>
</mat-chip-list>
</div>
<button (click)="fruitsUpdateDialog()">
Update Fruits
</button>
fruitsUpdateDialog() {
this.dialog.open(FruitsUpdateComponent, {
data: { selectedFruits: this.selectedFruits }
});
}
FruitsUpdateComponent - 这可以正确获取我想要的水果,但是当我从垫片中取出水果时,Fruits Component Html 会自动更新,这是我不想要的。我只想将 Fruits html 中的数据传递给 fruits update 而不是其他方式。我该如何解决?
export class FruitsUpdateComponent implements OnInit {
visible = true;
selectable = true;
removable = true;
separatorKeysCodes: number[] = [ENTER, COMMA];
fruitFormControl = new FormControl();
fruits: any;
allFruits: any;
@ViewChild('fruitInput', { static: false }) fruitInput: ElementRef<
HTMLInputElement
>;
@ViewChild('auto', { static: false }) matAutocomplete: MatAutocomplete;
constructor(
@Inject(MAT_DIALOG_DATA) public data) {
this.allFruits = //All Fruits JSON;
};
}
ngOnInit() {
this.fruits= this.data.selectedFruits;
}
remove(fruit: string, index): void {
this.fruits.splice(index, 1);
}
selected(event: MatAutocompleteSelectedEvent): void {
this.fruits.push(event.option.value);
this.fruitInput.nativeElement.value = '';
this.fruitFormControl.setValue(null);
}
HTML
<mat-dialog-content>
<mat-form-field>
<mat-chip-list #chipList>
<mat-chip
*ngFor="let fruit of fruits ; let fruitIndex= index"
[selectable]="selectable"
[removable]="removable"
(removed)="remove(fruit , fruitIndex)"
>
{{ fruit }}
</mat-chip>
<input
placeholder="What"
#fruitInput
[formControl]="fruitFormControl"
[matAutocomplete]="auto"
[matChipInputFor]="chipList"
[matChipInputSeparatorKeyCodes]="separatorKeysCodes"
/>
</mat-chip-list>
<mat-autocomplete
#auto="matAutocomplete"
(optionSelected)="selected($event)"
>
<mat-option *ngFor="let fruit of allFruits" [value]="fruit">
{{ fruit }}
</mat-option>
</mat-autocomplete>
</mat-form-field>
</mat-dialog-content>
所以水果被正确地传递到我想要的对话框中,但是当我从垫子中取出水果时,水果组件 Html 会自动更新,这是我不想要的。我只想将 Fruits html 中的数据传递给 fruits update 而不是其他方式。我只想要一种方式绑定。我该如何解决?
解决方案
原因是,您将一个对象传递给对话框组件,并且由于 javascript 对象通过引用工作,因此如果您的对象在对话框组件中发生了更改,它也会在您的主组件中发生更改。所以将数据传递给对话框的最佳方法是使变量不可变。
在你的 fruits.component.ts
fruitsUpdateDialog() {
this.dialog.open(FruitsUpdateComponent, {
// map function will return copy of original fruits.but it
// will not point to same reference
const tempFruits = this.selectedFruits.map(fruit => fruit);
data: { selectedFruits: tempFruits }
});
}
推荐阅读
- data-structures - 在用于线性探测的数组已满后添加元素
- unity3d - 当父对象为新父对象时,如何自由(内部)移动子对象?
- pytorch - LibTorch 中的固定内存
- kotlin - 在 Kotlin 中实现继承时,是否可以封装 open 和 override 变量以防止从 main() 函数直接访问?
- rancher - etcd 备份到内部 S3
- javascript - 为什么我需要在 JavaScript 的“setTimeout”中传递匿名函数?
- android - 将形状设置为 ImageView 背景以获得圆角
- three.js - 三.JS | GLSL 降档多边形 GLSL 粒子
- javascript - React JS:“消息”未定义 react/jsx-no-undef
- reactjs - 反应功能组件重新渲染一次,即使状态的值没有改变