我在Angular4中有一些经验,但我只是继承了一段使用FormControls的代码,我不知道如何使用它们。我正在设置一个注释textarea,如果isRegulatoryAuditRequired的值等于false,则需要该注释。我已经完成了所需的字段工作,但我需要显示消息'所需的评论'如果值为false并且提交了表单。这是我的HTML,有两个单选按钮,一个textarea和一条消息标签:
<div class="btnWrapper">
<div class="leftBtn">
<span class="col-xs-12 no-padding">
<label>
<input type="radio" id="radio1" class="app-input-radio" name="isRegulatoryAuditRequired" [value]="true"
[checked]="isRegulatoryAuditRequired==true" formControlName="isRegulatoryAuditRequired" />
<span class="app-input-radio pull-left"></span>
<span class="plx5 pull-left radioText ">Yes</span>
</label>
</span>
</div>
<br />
<div class="rightBtn">
<span class="col-xs-12 no-padding">
<label>
<input type="radio" id="radio2" class="app-input-radio" name="isRegulatoryAuditRequired" [value]="false"
[checked]="isRegulatoryAuditRequired==false" formControlName="isRegulatoryAuditRequired" />
<span class="app-input-radio pull-left"></span>
<span class="plx5 pull-left radioText ">No</span>
</label>
</span>
</div>
</div>
</div>
</div>
</div>
<div class="row mbx20">
<div class="col-sm-4">
<div>
<label>Why is the regulatory audit being performed or provide additional comment?</label>
<div>
<textarea id="comments" name="Text1" [required]="isRegulatoryAuditRequired==false" cols="100" rows="2" formControlName="comments"></textarea>
<label *ngIf="commentsRequired('comments')" style="color:red;font-weight:bold">Comments required</label>
</div>
我需要评估&#39; isRegulatoryAuditRequired&#39;和评论&#39; FormControls,看看我是否应该显示所需的评论&#39;信息。这是我尝试使用的方法,但它不起作用:
commentsRequired(controlName: string) {
const control = (<FormControl>this.rotationForm.controls[controlName]);
const isRegulatoryAuditRequired = (<FormControl>this.rotationForm.controls['isRegulatoryAuditRequired']);
if (isRegulatoryAuditRequired.value === false && control.value === '' && this.formSubmitAttempt) {
return true;
} else {
return false;
}
}
&#39; isRegulatoryAuditRequired.value&#39;和&#39; control.value&#39;打印到控制台为null,因此不显示消息。如何检索这些值?任何帮助将不胜感激。
答案 0 :(得分:7)
你可以做this.rotationForm.get('comments').value
这会给你formControl的值,然后你可以检查长度
答案 1 :(得分:0)
查看高级实现并使用几个步骤:
StackBlitz网址:https://stackblitz.com/edit/angular-kqz4nw
答案 2 :(得分:0)
在组件的FormGroup级别进行验证
this.loginForm = new FormGroup({
'email': new FormControl('example@example.com', Validators.compose([
Validators.required,
Validators.pattern('^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$')
])),
我能够在函数中像这样提取电子邮件值:
email = this.loginForm.value.email
为我工作-希望能为您提供帮助。