面试题答案
一键面试- 获取属性值的原理:
- 在Angular自定义指令中,可以通过
ElementRef
来访问宿主元素,进而获取其属性值。也可以使用@Input()
装饰器来获取宿主元素上绑定的值。
- 在Angular自定义指令中,可以通过
- 使用
ElementRef
获取属性值:- 首先,需要在指令类中注入
ElementRef
。 - 示例代码如下:
import { Directive, ElementRef } from '@angular/core'; @Directive({ selector: '[appCustomDirective]' }) export class CustomDirective { constructor(private el: ElementRef) { const dataInfoValue = this.el.nativeElement.getAttribute('data - info'); console.log('Using ElementRef, data - info value:', dataInfoValue); } }
- 首先,需要在指令类中注入
- 使用
@Input()
装饰器获取属性值:- 在指令类中定义一个输入属性,并在宿主元素上绑定该属性。
- 示例代码如下:
import { Directive, Input } from '@angular/core'; @Directive({ selector: '[appCustomDirective]' }) export class CustomDirective { @Input('data - info') dataInfoValue: string; constructor() { console.log('Using @Input, data - info value:', this.dataInfoValue); } }
- 在模板中使用指令时,如下绑定:
<div appCustomDirective data - info="some value"></div>