Angular 2/4/5/6 [(ngModel)]单选按钮未在后退按钮上选中

时间:2018-08-28 17:47:18

标签: angular typescript angular2-forms

我是Angular 2的新手。

我有一个带有单选按钮的表格。当我单击保存按钮时,它会转到下一个#页。从那里,如果我按下“后退”按钮,则不会选中选中的单选按钮。

我正在从JSON文件获取数据以创建单选按钮的名称和值。

这是我的html文件

<div class="card--content" *ngFor="let item of data; let i=index;">
    <input type="radio" #chocolate="ngModel" required name="chocolate" [(ngModel)]="chocolateType" [value]="item" id="select-{{i}}" checked="checked">
    <label for="select-{{i}}"></label>
    <img src="{{item.img}}" class="img-round" />
    <p class="text3">{{item.title}}</p>
 </div>

这是我的TypeScript文件:

Component({
    selector: 'app-select-chocolate',
    templateUrl: './select-chocolate.component.html',
    styleUrls: ['./select-chocolate.component.scss']
})
export class SelectChocolateComponent implements OnInit {
    chocolateType: string;
    form: any;
    data;
    constructor(private router: Router, private formDataService: FormDataService, private userService: UserService) { }

    ngOnInit() {
        document.body.className = "bg-gray01";
        this.userService.getChocolates()
            .subscribe(
                data => {
                    this.data = data;
                },
                error => {
                    console.log(error);
                }
            )
            //this.chocolateType = this.formDataService.getChocolate();
    }
    ngOnDestroy() {
        document.body.className = "";
    }
    save(form: any): boolean {
        if (!form.valid) {
            return false;
        }
        this.formDataService.setChocolate(this.chocolateType);
        return true;
    }

    goToNext(form: any) {
        if (this.save(form)) {
            // Navigate to the address page
            this.router.navigate(['/select-ingredients']);
        }
    }
}

我还创建了一项服务,以创建用户选择的formData

{
    "finger": "4",
    "chocolate": {
        "id": 1,
        "title": "Milk Chocolate",
        "img": "http://localhost:3000/images/milk-chocolate.png"
    },
    "ingredient": {},
    "message": "",
    "packaging": ""
}

点击“保存”按钮后,将调用formDataService服务。最后,我必须发布所有formData

请指导我做错了什么。

0 个答案:

没有答案