[Angular] Using the platform agnostic Renderer & ElementRef

ElementRef:

ElementRef is a way to access native html element, notice that it only works for Broswer.

Render:

Render helps to take care of different platforms (mobile or browser). It is recommended to use Render to change DOM instead of using ElementRef directly.

        <label>
          Email address
          <input type="email" name="email" ngModel #email>
        </label>
export class AuthFormComponent implements AfterViewInit {

  @ViewChild('email') email: ElementRef;

  constructor(
    private renderer: Renderer
  ) {}

  ngAfterViewInit() {
    this.renderer.setElementAttribute(this.email.nativeElement, 'placeholder', 'Enter your email address');
    this.renderer.setElementClass(this.email.nativeElement, 'email', true);
    this.renderer.invokeElementMethod(this.email.nativeElement, 'focus');
    // this.email.nativeElement.setAttribute('placeholder', 'Enter your email address');
    // this.email.nativeElement.classList.add('email');
    // this.email.nativeElement.focus();
  }

...

}

Another example:

this.loadingService.duration: '2s'

//from   
  this.el.nativeElement.style.setProperty(
      "--duration",
      this.loadingService.duration
    );


// to
    this.render.setAttribute(
      this.el.nativeElement,
      "style",
      `--duration:${this.loadingService.duration}`
    );
原文地址:https://www.cnblogs.com/Answer1215/p/6436461.html