如何使用 Angular 2+ 中的指令获取图像 src 值?
How can I get an image src value using a directive in Angular 2+?
根据标题,我想了解如何使用目录获取图像 src 值
指令:
@Directive({
selector: '[appLazyImage]',
})
export class LazyImageDirective implements OnInit {
@HostBinding('src') public src: string;
@Input() private appLazyImage: string;
constructor() {}
public ngOnInit() {
//this.src is undefined
console.log(this.appLazyImage, this.src);
}
}
Html:
<img [appLazyImage]="'test'" class="product-content-image__img" [src]="{{url}}" alt="{{alt}}" title="{{title}}" />
使用 ElementRef 服务获取 Src 属性
import { Directive, ElementRef } from '@angular/core';
@Directive({
selector: '[appSrc]'
})
export class SrcDirective {
constructor(private el: ElementRef) {
console.log(this.el.nativeElement.src);
}
}
使用 nativeElement
获取属性值。
constructor(elm: ElementRef) {
let src = elm.nativeElement.getAttribute('src');
}
根据标题,我想了解如何使用目录获取图像 src 值
指令:
@Directive({
selector: '[appLazyImage]',
})
export class LazyImageDirective implements OnInit {
@HostBinding('src') public src: string;
@Input() private appLazyImage: string;
constructor() {}
public ngOnInit() {
//this.src is undefined
console.log(this.appLazyImage, this.src);
}
}
Html:
<img [appLazyImage]="'test'" class="product-content-image__img" [src]="{{url}}" alt="{{alt}}" title="{{title}}" />
使用 ElementRef 服务获取 Src 属性
import { Directive, ElementRef } from '@angular/core';
@Directive({
selector: '[appSrc]'
})
export class SrcDirective {
constructor(private el: ElementRef) {
console.log(this.el.nativeElement.src);
}
}
使用 nativeElement
获取属性值。
constructor(elm: ElementRef) {
let src = elm.nativeElement.getAttribute('src');
}