First, assign a reference variable i.e. #companyname to the HTML element as followings

<input class="form-control" #companyname placeholder="Enter a Name">

Second, in the Component where you want to access the DOM, use @ViewChild together with the reference variable to access the DOM.

@ViewChild('companyname')

The above-mentioned @ViewChild('companyname') is a decorator to a variable of the Component. The variable type is ElementRef.

app/app.component.ts
import { Component, AfterViewInit, ViewChild } from '@angular/core';

@Component({
  selector: 'cloudberry-app',
  template: `<input class="form-control" #companyname placeholder="Enter a Name">`,
})
export class AppComponent implements AfterViewInit {
  @ViewChild('companyname') companyNameInput: ElementRef;
}

Third, in the ngAfterViewInit(), implement codes to change the value of the input element with Renderer.

app/app.component.ts
import { Component, AfterViewInit, ElementRef, ViewChild, Renderer2 } from '@angular/core';

@Component({
  selector: 'cloudberry-app',
  template: `<input class="form-control" #companyname placeholder="Enter a Name">`
})
export class AppComponent implements AfterViewInit {
  @ViewChild('companyname') companyNameInput: ElementRef;
  
  constructor(private renderer: Renderer2) { }
  
  ngAfterViewInit(){
    this.renderer.setAttribute(this.companyNameInput.nativeElement, "value", "CloudBerry System"); 
  }
}
Renderer and ElementRef have to be used together to get full platform abstraction.

Example

References:
https://angular.io/api/core/Renderer2
https://angular.io/api/core/ElementRef

Last modified: December 4, 2017

Author