[英]How to save radio button click, when I use *ngFor?
When I click on the radio button, I go to another view (routes) and come back, the radio button is didn't clicked.当我点击单选按钮时,我 go 到另一个视图(路线)并返回,单选按钮没有被点击。 How to fix it?
如何解决? I use *ngFor to display data of radio buttons.
我使用 *ngFor 来显示单选按钮的数据。
order-shipping.component.html:订单发货.component.html:
<div class="card-header">
<input type="radio" name='shipping' (click)="calculatePrices.emit(shipping.price)"> {{shipping.name}}
<p class="card-text"> price: {{shipping.price}}</p>
</div>
order-shipping.component.ts: order-shipping.component.ts:
export class OrderShippingComponent implements OnInit {
@Input() shipping;
@Output() calculatePrices = new EventEmitter();
constructor() { }
ngOnInit() { }
}
order.component.html: order.component.html:
<app-order-shipping *ngFor="let shipping of shippings" [shipping]="shipping"
(calculatePrices)="this.cartService.calculatePrices($event)"> </app-order-shipping>
order.component.ts: order.component.ts:
export class OrderComponent implements OnInit {
items = {};
shippings = [];
constructor(private cartService: CartService,
private shippingService: ShippingService) { }
ngOnInit() {
this.items = this.cartService.getItems();
this.shippingService.getShipping()
.subscribe(
res => this.shippings = res,
err => console.log(err)
);
}
}
You will need a way to save the selected option on exit.您将需要一种在退出时保存所选选项的方法。 The easiest way is to use a service
最简单的方法是使用服务
We create a simple service with 2 properties, a BehaviorSubject
and an Observable
deriving its value from the BehaviorSubject
我们创建一个具有 2 个属性的简单服务,一个
BehaviorSubject
和一个从BehaviorSubject
派生其值的Observable
export class OrderService {
constructor() { }
selectedOrderSubject$ = new BehaviorSubject<null | string>(null)
selectedOrder$ = this.selectedOrderSubject$.asObservable()
}
The next step is to read this value OnInit
and update this value OnDestroy
下一步是读取这个值
OnInit
并更新这个值OnDestroy
export class OrderComponent implements OnInit, OnDestroy {
shippings = ["Shipping A", "Shipping B"];
selectedShipping = "";
destroyed$ = new Subject();
calculatePrices(shipping) {
this.selectedShipping = shipping;
//this.cartService.calculatePrices($event)
}
ngOnInit() {
this.orderService.selectedOrder$
.pipe(takeUntil(this.destroyed$))
.subscribe({
next: order => (this.selectedShipping = order)
});
}
constructor(private orderService: OrderService) {}
ngOnDestroy() {
this.orderService.selectedOrderSubject$.next(this.selectedShipping);
this.destroyed$.next();
}
}
See this fork of @SalminSkenderovic stackblitz请参阅@SalminSkenderovic stackblitz 的这个分支
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.