首页 > 解决方案 > 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?

https://stackblitz.com/edit/angular-ylufjn

标签: angular

解决方案


尝试使用[attr.required]="required || null"而不是[required]="required ? '' : null"

更新的示例在这里 https://stackblitz.com/edit/angular-j7dgba?file=src%2Fapp%2Fhello.component.ts


推荐阅读