我正在尝试构建一种表单,该表单将获取可能以多种不同格式(每周,每月,其他)出现的调度信息。我正计划在表单的时间表部分中,用户通过单选按钮组选择时间表的类型。如果选择了“每周”选项,则会出现一组带有工作日的复选框,以便您可以选择星期几。如果是每月,则可以选择一个月中的某天,依此类推。我尝试使用* ngIf方式使事情出现,但它不起作用,并且没有收到任何错误消息。关于如何实现这一点的任何想法?
我正在使用: -角材料元素 -角2(8) -角反应形式
我已经实现了其中的一部分,下面是单选按钮的代码和我要隐藏的第一个计划部分(为代码格式不正确而道歉,仍在计算出堆栈溢出):
<form [formGroup] = "SchedInfo" (ngSubmit)="onSubmit()">
<mat-radio-group formControlName= "sType" (ngSubmit)= "onSubmit()">
<mat-radio-button type="radio" [value] ="true" [checked] = "value">Weekly</mat-radio-button>
<mat-radio-button type="radio" [value] ="false" [checked] = "!value">Monthly</mat-radio-button>
</mat-radio-group>
<div class = "weeklyS" *ngIf= "sType.value">
<br>
<!-- possibly need to resturcture the section below -->
<mat-checkbox formControlName= "mo">Monday</mat-checkbox>
<mat-checkbox formControlName= "tu">Tuesday</mat-checkbox>
<mat-checkbox formControlName= "we">Wednesday</mat-checkbox>
<mat-checkbox formControlName= "th">Thursday</mat-checkbox>
<mat-checkbox formControlName= "fr">Friday</mat-checkbox>
<mat-checkbox formControlName= "sa">Saturday</mat-checkbox>
<mat-checkbox formControlName= "su">Sunday</mat-checkbox>
</div>
最后,我的目标是要有一个计划模块,可以在几种不同的输入方法之间切换。
也:
每次选择更改时,我应该都填充一个div,还是应该根据选择显示/隐藏多个div?
答案 0 :(得分:0)
您实际需要做的是正确绑定无线电的值以及如何取回该值。这是我能想到的简单示例。
首先我们的模板代码
<form [formGroup]="myForm" (submit)="onSubmit(myForm.value)" novalidate>
<label id="example-radio-group-label">Pick your Type</label>
<mat-radio-group class="example-radio-group" formControlName="sType">
<mat-radio-button class="example-radio-button" *ngFor="let sfType of scheduleTypes" [value]="sfType">
{{sfType}}
</mat-radio-button>
</mat-radio-group>
<ng-container [ngSwitch]="getScheduleType()">
<div *ngSwitchCase="'Weekly'">
Weekly Content
</div>
<div *ngSwitchCase="'Monthly'">
Monthly Content
</div>
</ng-container>
</form>
现在的组件代码:
import { Component, OnChanges, OnDestroy, OnInit, Output, ViewChild } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
export interface DataModel {
sType: string;
}
/**
* @title Radios with ngModel
*/
@Component({
selector: 'radio-ng-model-example',
templateUrl: 'radio-ng-model-example.html',
styleUrls: ['radio-ng-model-example.css'],
})
export class RadioNgModelExample {
myForm: FormGroup;
//List of the schedule types. You might want to change this to an ENUM
scheduleTypes: string[] = ['Weekly', 'Monthly'];
constructor(private formBuilder: FormBuilder) {
this.buildForm();
}
//Remember to build your form properly
public buildForm() {
this.myForm = this.formBuilder.group({
sType: [null]
});
}
public onSubmit(data: DataModel) {
//Submit Data Here
}
public getScheduleType() {
//Get the value of your stypeControl
return this.myForm.controls['sType'].value;
}
}