Conditionally add an element attribute in knockout.js

The knockout.js library has an "attr" data binding which allows you to dynamically change the value of an HTML element attribute (e.g. the "title"). However, in some cases, the attribute may or may not be needed depending on the corresponding observable on the bound object. For example, if my model has a "title" observable I might want to set the "title" attribute if it is present (non-null) or skip the attribute entirely if it is not present (null).

Does knockout provide any way to conditionally set an attribute? (Ideally without conditionally rendering the entire element opening tag...)

[Note] This similarly named question was actually resolved by knockout's special handling of CSS classes and does not relate to this question (or its own title): How to conditionally render an css class with knockoutjs


I needed this when selecting an (that I was generating manually instead of built-in knockout).

 data-bind="text: text, 
     'selected': typeof(selected) !== 'undefined' ? selected : null 
 Choice X

This says to always update the 'text' attribute and to add the 'value' attribute, but only add 'selected' if the the data already has a value of 'selected' defined.

You can create a custom binding attrIf which will check the value of a specific observable boolean before add or not the attributes. See this example:

ko.bindingHandlers.attrIf = {
    update: function (element, valueAccessor, allBindingsAccessor) {
        var h = ko.utils.unwrapObservable(valueAccessor());
        var show = ko.utils.unwrapObservable(h._if);
        if (show) {
            ko.bindingHandlers.attr.update(element, valueAccessor, allBindingsAccessor);
        } else {
            for (var k in h) {
                if (h.hasOwnProperty(k) && k.indexOf("_") !== 0) {

<a href="#" data-bind="attrIf: {title: title, _if: flag}">link</a>

Knockout's "attr" data binding does support this scenario just return null or undefined from your getDisabledState() function then it won't emit the attribute.

This answer was retrieved from Knockout attr binding with attributes like 'readonly' and 'disabled'

I wish I could have just replied to @gbs, but I can't. My solution would have been to have two of the same HTML element, one with the attribute, one without, and a knockout condition to add one of it according to the element. I also know about this custom biding, but which of the solution is more efficient?

Need Your Help

NSAttributedString add text alignment

ios objective-c nsattributedstring core-text

How can I add text alignment attribute to an NSAttributedString to center the text?

Android Application Error while running the Application

java android

Whenever I try running my application - this window in the screenshot is popping up in my screen. Stating that default activity is not found because of this I am not able to deploy my app: