面试题答案
一键面试- 获取自定义属性值的方法:
- 在Angular自定义指令中,可以通过
ElementRef
来获取宿主元素,进而获取其属性值。也可以使用@HostBinding
和@HostListener
相关的装饰器来处理宿主元素的属性和事件等,这里我们用ElementRef
来获取data - custom
属性值。
- 在Angular自定义指令中,可以通过
- 关键代码示例:
在上述代码中:import { Directive, ElementRef, OnInit } from '@angular/core'; @Directive({ selector: '[appCustomDirective]' }) export class CustomDirective implements OnInit { constructor(private elementRef: ElementRef) {} ngOnInit() { const customValue = this.elementRef.nativeElement.getAttribute('data - custom'); console.log('自定义属性data - custom的值为:', customValue); } }
- 首先通过依赖注入将
ElementRef
注入到指令的构造函数中。 - 在
ngOnInit
生命周期钩子函数中,使用elementRef.nativeElement.getAttribute('data - custom')
来获取data - custom
属性的值,并通过console.log
打印出来。实际应用中,可以根据需求对获取到的值进行进一步处理。
- 首先通过依赖注入将