Search⌘ K
AI Features

Solution: Introduction to Attribute Directives

Explore the solution of creating a custom Angular attribute directive that modifies image element styles using ElementRef. Understand how to target specific elements and apply dynamic styling to improve UI behavior.

We'll cover the following...

Solution

Here’s an example of what the solution for this task may look like:

import { Directive, ElementRef, OnInit } from '@angular/core';

@Directive({
  selector: 'img[appAvatar]'
})
export class AvatarDirective implements OnInit {

  constructor(private elementRef: ElementRef) {
  }

  ngOnInit() {
    const size = '72px';
    this.elementRef.nativeElement.style.width = size;
    this.elementRef.nativeElement.style.height = size;
    this.elementRef.nativeElement.style.border = `1px solid gold`;
    this.elementRef.nativeElement.style.borderRadius = size;
  }
}
The task’s solution

Explanation

The actual directive code is very similar to ...