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

前端 未结 7 1012
我在风中等你
我在风中等你 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: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

    
    

    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.

提交回复
热议问题