I'm having the issue where I'm getting the following error when trying to access a html element by ID. I'm attempting to access the classList when the user clicks a button to apply a different style class to the element. The class list and element in general are always null, unless I switch the viewEncapsulation back to the default emulated setting.
Error Message:
TypeError: Cannot read property 'classList' of null
Problem: I'm attempting to have this specific component not inherit a 3rd party SCSS file that I've imported into the project via the angular.json file. When I use default ViewEncapsulation.Emulated, the component is inheriting the global SCSS styles which is conflicting with some of the components styling.
The file structure is normal, I'm putting the SCSS and HTML in the corresponding files, then importing them into the component.
I feel like this should be a common theme to see with larger projects. If there's a different way to go about switching the styling of elements on events please let me know.
Component .ts:
import { Component, ViewEncapsulation, OnInit } from '@angular/core';
@Component({
encapsulation: ViewEncapsulation.Native,
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
title = 'scssTesting';
constructor() { }
step: string = 'step1';
step1: any;
step2: any;
step3: any;
ngOnInit() {
}
next() {
this.step1 = document.getElementById('step1');
this.step2 = document.getElementById('step2');
this.step3 = document.getElementById('step3');
if (this.step === 'step1') {
this.step = 'step2';
this.step1.classList.remove("is-active");
this.step1.classList.add("is-complete");
this.step2.classList.add("is-active");
} else if (this.step === 'step2') {
....
}
}
Component .scss
.progress {
position: relative;
display: flex;
.........
}
Component .html
<div class="container">
<div class="progress">
<div class="progress-track"></div>
<div id="step1" class="progress-step">
Step One
</div>
<div id="step2" class="progress-step">
Step Two
</div>
<div id="step3" class="progress-step">
Step Three
</div>
</div>
<button (click)="next()">Next Step</button>
</div>
@ViewChild()to get anElementReflike @Barbu Barbu and @cgTag suggested. Second of all, if you're already usingdocument, just know that it's unsafe to usedocumentdirectly in Angular. You should use dependency injection and@Inject(DOCUMENT)(importInjectfrom'@angular/core'andDOCUMENTfrom'@angular/common').