How to get/set/remove element attribute in Angular 2 using “the angular way”?

前端 未结 7 1008
我在风中等你
我在风中等你 2021-01-17 15:48

I\'ve been reading some articles about Angular 2 pitfalls and what to avoid, one of those things revolves around not accessing the DOM directly.

I noticed that the

相关标签:
7条回答
  • 2021-01-17 16:24

    Since getAttribute is just a method, you could use invokeElementMethod:

    var attr = renderer.invokeElementMethod(elementRef.nativeElement, 'getAttribute', []);
    

    This approach will not work if you switch to server-side rendering (except event callbacks like mouse click).

    Extending DOMRenderer effectively means tight coupling to browser implementation, which is the same as direct nativeElement manipulation.


    It seems that you should not invoke getters at all. So the question is why do you need to know attribute value or class name?

    You could create specific directive or template variable and use it with ViewChild/ViewChildren, or create appropriate data model and bind with [class.name]="nameEnabled"

    0 讨论(0)
  • 2021-01-17 16:28

    Angular2 doesn't provide any support to get anything from the DOM except ElementRef and events.
    The Angular2 way is to maintain the state in the model and update the DOM to reflect that state.

    If you need to read from the DOM you can use direct DOM access or provide a custom Renderer that provides the features you're missing in the default Renderer.

    Examples for custom renderers

    • Custom renderer for Angular2
    • https://github.com/ralfstx/angular2-renderer-example/blob/master/src/custom-renderer.ts
    0 讨论(0)
  • 2021-01-17 16:28

    To remove attributes from the DOM you provide a value of null.

    To set an attribute (attribute value can be an empty string if you wish):

    myrenderer.setElementAttribute(elementRef.nativeElement, 'attributename', 'attributevalue');
    

    To remove an attribute:

    myrenderer.setElementAttribute(elementRef.nativeElement, 'attributename', null);
    

    To get an element attribute value, you have the nativeElement which you pass to setElementAttribute, so you can use that to get the attribute value using standard Javascript:

    elementRef.nativeElement.getAttribute('attributename');
    
    0 讨论(0)
  • 2021-01-17 16:34

    Solution based on @RandallTo 's answer above.

    Angular

    ngAfterViewInit() {
          window.setTimeout(function () {
    
             const arr: HTMLCollection = document.getElementsByClassName('disable-autocomplete');
             for (let i = 0; i < arr.length; i++) {
                 arr[i].removeAttribute('readonly');
             }
    
       }, 500);
    }
    

    HTML

    <input type="text" name="username" readonly="" class="form-control disable-autocomplete"/>
    

    CSS

    .disable-autocomplete {
      background-color: #fff;
    }
    

    Adding the white background colour means that you won't get a flash as the form loads with readonly fields (which are grey by default) which then turn white when the readonly attribute is removed.

    You don't need the if statement in my version because you only set readonly and .disable-autocomplete on the fields for which you want to disable autocomplete.

    For example you might want to allow autocomplete on the email field but not in the username field.

    0 讨论(0)
  • 2021-01-17 16:35

    In case someone is still looking for this (as I did), i shall add up a bit on David's answer which was on Angular's native renderer.

    You have all this requested functionality in newest Angular Renderer2

    Particularly if you want to completely remove attributes (ex. invalid aria tags in community components that fail accessibility tests) from elements and not set their value to null, there is

    renderer2.removeAttribute(elementRef.nativeElement, 'AttributeName');
    

    EDIT: You should use AfterViewInit() lifecycle, as described in other answers, as the initial view must be rendered before you make any custom DOM changes.

    0 讨论(0)
  • 2021-01-17 16:39

    To remove a class, you still can use setElementClass, the isBool should be set to false. See this link for more info https://github.com/angular/angular/blob/9de76ebfa545ad0a786c63f166b2b966b996e64c/modules/%40angular/platform-browser/src/dom/dom_renderer.ts#L237

    0 讨论(0)
提交回复
热议问题