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

前端 未结 7 1068
我在风中等你
我在风中等你 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: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');
    

提交回复
热议问题