Can't bind to 'disabled' since it isn&

2020-02-10 00:57发布

问题:

I added [disabled] property to li element. But I get this error:

Can't bind to 'disabled' since it isn't a known property of 'li'.

This is my code part:

<li [disabled]="pager.currentPage > 1">
</li>

Can anyone help me?

回答1:

The <li> element doesn't have a disabled property.
Either a component or directive that you expect to be applied to <li was actually not applied, or perhaps the disabled attribute should be set instead of the property

<li [attr.disabled]="pager.currentPage > 1 ? true : null">

null is to get the attribute removed in case the condition is false. A boolean false would lead to

<li disabled="false">

which might not what you want. With null you get

<li>


回答2:

To add the Gunter's answer. Disabled property only makes sense for html tags that have actions that could be disabled.

Disabled elements

An element is said to be actually disabled if it falls into one of the following categories:

  • button elements that are disabled
  • input elements that are disabled
  • select elements that are disabled
  • textarea elements that are disabled
  • optgroup elements that have a disabled attribute
  • option elements that are disabled
  • fieldset elements that have a disabled attribute

https://www.w3.org/TR/html5/disabled-elements.html

So doesn't make sense to make a li disabled because it doesn't have any actions to begin with.

Another way to understand this that disabled property is actually an @Input property that is defined by form related directives, like FormControl or FormControlName and ... , so if you don't use those directives, you can't have disabled attributes.

For example , an input can have disabled property because it can have NgModel , but an li or a div cannot have disabled attribute, because it can never have a NgModel!

So for [disabled] to work , angular would check for two things :

1- Is disabled a directive defined by Angular2 or defined by you ? ( no ) .

2- Is disabled an @input that is defined by another directive that is used at the the same level in the tag ( like NgModel , FormControl and ..) ? ( yes it is defined , but you're not using them because li cannot have FormControl ! ).

So then Angular2 would throw an error.

Where as , when you do [attr.disabled] , this is not a @Input anymore and it's just a normal html attribute like all the other normal attributes.

So if you only need disabled property as a normal html attribute to do some css stuff with it , you should use [attr.disabled].



标签: angular