angular2模型驱动形式单选按钮问题

时间:2017-03-27 17:18:51

标签: angular angular2-forms

我遇到一个问题,就是让单选按钮在我的被动表单中正常工作。这是我的组件代码:

** WARNING ** Getting caught editing the TFS database directly
** will void your Microsoft Support Agreement. **
** Proceed at your own risk. **

以下是我的模板的一部分,其中包含以下表单:

export class SettingsFormComponent implements OnInit {

    public sForm: FormGroup;
    public submitted: boolean;
    diagramSettings: DiagramSettings;


    constructor(private _formBuilder: FormBuilder, private _settingsService: SettingsService) {

        this._settingsService.diagramSettingsSubject.subscribe((dSettings: DiagramSettings) => {
            this.diagramSettings = dSettings;
        });


        this.sForm = new FormGroup({
            hoverDelay: new FormControl('', [<any>Validators.required, CustomValidators.range([500, 2000])]),
            hoverAction: new FormControl('', []),
            leftClickAction: new FormControl('', []),
            rightClickAction: new FormControl('',[])
        });

        this.sForm.setValue({
            hoverDelay: this.diagramSettings.hoverDelay,
            hoverAction: this.diagramSettings.OnHover,
            leftClickAction: this.diagramSettings.OnLeftClick,
            rightClickAction: this.diagramSettings.OnRightClick
        });

        //this.sForm = new FormGroup({
        //    hoverDelay: new FormControl(500, [<any>Validators.required, <any>Validators.minLength(3)])
        //});

    }

    ngOnInit() {

    }

    save() {

        this.submitted = true; // set form submit to true

        this._settingsService.setOpen(false);

        // check if model is valid
        // if valid, call API to save customer
        console.log('in model save. ');
    }

}

UI单选按钮似乎工作,当你在它们之间切换时只检查一个等等。问题是它似乎没有绑定到我的hoverAction formControl,因为该值总是=== 0(其中是它初始化的值)。 hoverDelay文本输入绑定到表单控件并进行适当更新,因此我必须使用单选按钮进行操作。

如何使用带有角度2反应形式的单选按钮?

1 个答案:

答案 0 :(得分:0)

[class]绑定用于应用和删除css样式[1],所以我认为你不能在其中执行任何逻辑。您应该使用(click)事件:

    <label class="btn btn-primary" (click)="sForm.value.hoverAction === 1">
        <input type="radio"  name="hoverAction" value="1" formControlName="hoverAction" />Modal
    </label>
    <label class="btn btn-primary" (click)="sForm.value.hoverAction === 2">
        <input type="radio" name="hoverAction"  value="2" formControlName="hoverAction" />Navigate
    </label>
    <label class="btn btn-primary" (click)="sForm.value.hoverAction === 0">
        <input type="radio"  name="hoverAction" value="0" formControlName="hoverAction" />Do Nothing
    </label>