angular - Problem with conditional required attribute in Angular
问题描述
Fairly new to Angular.
I'm trying to mark an input field with an optional "required" attribute, which will be controlled by a property of the same name in the component.
@Input() required: boolean = true;
Simple, right? That's what I thought.
This is working:
<input
id="test123" name="test123"
[required]="required ? '' : null"
[(ngModel)]="test123"
/>
Whereas this is not:
<input
id="test456" name="test456"
[required]="required ? '' : null"
/>
Obviously, it needs an ngModel for the required to work, but I don't really need a model for this input; I'm just using the input for capturing keyboard events for an auto-complete.
Should I just make a fake model for it in the component? Or is there another way around this?
解决方案
尝试使用[attr.required]="required || null"
而不是[required]="required ? '' : null"
更新的示例在这里 https://stackblitz.com/edit/angular-j7dgba?file=src%2Fapp%2Fhello.component.ts
推荐阅读
- flutter - 颤振错误:值可以为“空”的表达式必须先进行空检查,然后才能取消引用
- python - 如何用两个值的总和在特定列中填充 NA?
- angular - 获取以日期为参数的请求 Angular 8 (ts) + .NET Core
- javascript - 无法使用 Screen Capture API 录制音频
- java - Java证书链验证-适用于自签名证书和委托签名证书失败
- linux - 权限被拒绝(公钥),在 Linux AWS 服务器上我可以修复它吗?
- python - 从 lambda DynamoDB 获取字符串值
- twilio - Twilio Say vs Play 动词表现
- java - Java LongCache 返回错误值
- php - PHP分页显示页码两次