我遇到的問題是,當我嘗試通過ID訪問html元素時,我遇到以下錯誤。當用戶單擊按鈕以將不同的樣式類應用于元素時,我正在嘗試訪問classList。除非我將viewEncapsulation切換回默認的模擬設置,否則類列表和元素通常都是null。錯誤消息:TypeError: Cannot read property 'classList' of null問題:我試圖讓這個特定的組件不繼承我通過angular.json文件導入到項目中的第三方SCSS文件。當我使用默認的ViewEncapsulation.Emulated時,該組件繼承了與某些組件樣式沖突的全局SCSS樣式。文件結構是正常的,我將SCSS和HTML放在相應的文件中,然后將它們導入到組件中。我覺得這應該是一個與大型項目相關的共同主題。如果有不同的方法來切換事件元素的樣式,請告訴我。組件.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') {
....
}}組件.scss.progress {
position: relative;
display: flex;
.........}組件.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>
Angular - 如何在使用ViewEncapsulation.Native時訪問html元素
慕絲7291255
2019-04-12 14:15:17