出于某种原因,当我在console.log中选择一个用户的单选按钮时,对控制台的日志始终是落后的。 为什么会这样? 我有一个默认的单选按钮选择设置为初始状态的“全部”。 当用户单击“选项A”时,登录到控制台的是从初始状态开始的“全部”。 当我再次点击时,这次在“选项B”上,什么日志是前一个选择中的“选项A”。 为什么一次性? 我该如何解决这个问题?
public user: User; public categories = [ { value: 'T', display: 'All', count: 232 }, { value: 'A', display: 'Choice A', count: 22 }, { value: 'B', display: 'Choice B', count: 43 }, { value: 'C', display: 'Choice C', count: 35 }, { value: 'D', display: 'Choice D', count: 62 }, ]; ngOnInit() { this.user = { category: this.categories[0].value } } select(isValid: boolean, f: User) { if (!isValid) return; console.log(f); console.log(this.user.category); }和HTML:
<form #f="ngForm" novalidate> <div class="form-group"> <div class="radio" *ngFor="let category of categories"> <label> <input type="radio" name="category" [(ngModel)]="user.category" [value]="category.value" (click)="select(f.value, f.valid)"> {{category.display}} </label> <span class="num-results">{{category.count}}</span> </div> </div> </form>For some reason, when I console.log a user's radio button selection, what logs to the console is always one behind. Why would this be? I have a default radio button selection set to "all" for the initial state. When a user click's "Option A" what logs to the console is the "all" from the initial state. When I click again, this time on "Option B", what logs is "Option A" from the previous selection. Why is it one off? How can I resolve this?
public user: User; public categories = [ { value: 'T', display: 'All', count: 232 }, { value: 'A', display: 'Choice A', count: 22 }, { value: 'B', display: 'Choice B', count: 43 }, { value: 'C', display: 'Choice C', count: 35 }, { value: 'D', display: 'Choice D', count: 62 }, ]; ngOnInit() { this.user = { category: this.categories[0].value } } select(isValid: boolean, f: User) { if (!isValid) return; console.log(f); console.log(this.user.category); }And the HTML:
<form #f="ngForm" novalidate> <div class="form-group"> <div class="radio" *ngFor="let category of categories"> <label> <input type="radio" name="category" [(ngModel)]="user.category" [value]="category.value" (click)="select(f.value, f.valid)"> {{category.display}} </label> <span class="num-results">{{category.count}}</span> </div> </div> </form>最满意答案
使用ngModelChange而不是click
(ngModelChange)="select(f.value, f.valid)"在ngModel有机会更新表单之前处理(click)事件。
元素上的绑定顺序不定义事件的处理顺序。
Use ngModelChange instead of click
(ngModelChange)="select(f.value, f.valid)"The (click) event is processed before ngModel had the chance to update the form.
The order of bindings on an element doesn't define in what order events are processed.
更多推荐
发布评论